c++ 变量声明和定义

Declarations and Definitions

To support separate compilation, C++ distinguishes between declarations and definitions.

A declaration makes a name known to the program. A file that wants to use a name defined elsewhere includes a declaration for that name.

A definition creates the associated entity.

A variable declaration specifies the type and name of a variable.

A variable definition is a declaration. In addition to specifying the name and type, a definition also allocates storage and may provide the variable with an initial value.

To obtain a declaration that is not also a definition, we add the extern keyword and may not provide an explicit initializer:

extern int i; // declares but does not define i
int j; // declares and defines j  !!!!

Note:
Variables must be defined exactly once but can be declared many times.

To use a variable in more than one file requires
declarations that are separate from the variable’s definition.
To use the same variable in multiple files, we must define that variable in one—and only one—file. Other files that use that variable must declare—but not define—that variable.

Difference between declaration and definition

What is the difference between a definition and a declaration?

What is the difference between declaration and definition of a variable in C++?

Declare vs Define in C and C++

The differences between initialize, define, declare a variable

Static Typing

C++ is a statically typed language, which means that types are checked at compile time.

The process by which types are checked is referred to as type
checking
.

As we’ve seen, the type of an object constrains the operations that the object can perform.

In C++, the compiler checks whether the operations we write are supported by the types we use.

If we try to do things that the type does not support, the compiler generates an error message and does not produce an executable file.

As our programs get more complicated, we’ll see that static type checking can help find bugs.

However, a consequence of static checking is that the type of every entity we use must be known to the compiler.

As one example, we must declare the type of a variable before we can use that variable.

发布了120 篇原创文章 · 获赞 2 · 访问量 5781

猜你喜欢

转载自blog.csdn.net/Lee567/article/details/104081153