Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to define variables in C++
How to define variables in C++

To put it simply: if you want to define an integer variable, just type "type variable name;". For example, define an integer variable called a

"int a;"

Detailed description:

In C++, variable declaration (declaration) can only be made using extern This is true only if the keyword is used. In other cases, it is a definition. When using extern and assigning an initial value to a variable, the declaration becomes a definition, and the extern keyword will also be ignored by the compiler. The scope of C++ variables is global by default, that is, it is visible to multiple source files, for example, if it exists in a.cpp and b.cpp

int a;

The compiler will report an error when linking the two files, "Variable is repeatedly defined". Therefore, to make the variable definition visible only to the source file, the static keyword must be explicitly added. Therefore, we can think of, if there is

extern int a;

in a.cpp and there is

static int a = 9 in b.cpp ;

Then, the compiler will give an error message when linking, "the definition of a cannot be found", because the definition of a is in b.cpp and is only visible to this file, and a.cpp cannot be found The definition of a is therefore wrong.

The declaration and definition of variables are concepts that are easily confused, so remember that unless there is the extern keyword, they are all definitions of variables. From this, we can summarize several good programming styles:

1. Do not put variable definitions into .h files, as this can easily lead to repeated definition errors.

2. Try to use the static keyword to limit the variable definition to the scope of the source file, unless the variable is designed to be global.

Exceptions are const variables and typedef types. As mentioned in Section 9.2 of "The C++ Programming Language", the default scope of const and typedef is local, so there is no need for static to be explicitly declared. Therefore, placing a const variable definition in a .h file will not cause problems. The compiler will generate a local definition of the const variable for each source file that references the .h file, just as if the variable was defined in the source file. Same as in. You don’t have to worry too much about the compiler wasting space by doing this, because the compiler optimization process generally merges const variables with the same value.

Regarding the static keyword, I want to say a few more words. Static generally has two meanings. When modifying variables in function definitions or class member variables, it is called static variables; when modifying other variables, called local variables. To prevent confusion, generally do not specifically add the static keyword to local variables. In addition to the static keyword, namespace can also make variable definitions local.