Const
By default, a variable is a local variable of the file that defines the variable. As we can see now, the reason for setting the default condition is to allow the const
Variables are defined in the header file.
In C ++
In some cases, constant expressions must be placed. For example, the initialization type of the enumerated member must be a constant expression. In the following sections, we will see examples of other constant expressions. In general, constant expressions are the expressions that the compiler can calculate at compilation. When const
The const
An integer variable may be a constant expression. While const
To make a variable a constant expression, the initialization must be visible to the compiler. To allow multiple files to use the same constant value, const
The variable and its initialization type must be visible to every file. To make the initialization visible, such const
Variables are defined in the header file. In that case, regardless of the const
When to use a variable, the compiler can see its initialization method. However, C ++
Any variable in can be defined only once. Definition will allocate a bucket, and all usage of this variable will be associated with the same bucket. Because const
Objects are local variables of their files by default, so it is legal to put their definitions in header files. This behavior has a very important meaning: when we define the const in the header file
After the variable, each source file containing the header file has its own const
Variable with the same name and value. When the const
When a variable is initialized using a constant expression, it can ensure that all variables have the same value. However, in practice, most compilers Replace the const with corresponding constant expressions during compilation.
Any usage of the variable. Therefore, in practice, no storage space is used to store the const initialized with a constant expression.
Variable. If const
Variables are not initialized using constant expressions, so they should not be defined in the header file. On the contrary, like other variables, the const
Variables should be defined and initialized in a source file. Add extern to the header file.
Declaration, so that it can be shared by multiple files.