Description and definition of variables in C Language
For many beginners, the definition and declaration of variables are not recommended. C and C ++ are slightly different, and const, static, and extern are even more chaotic, the following is a detailed explanation and example.
Variable definition: allocate storage space for the variable and specify the type and name of the variable. In addition, the initialization of a variable is to give a value at the definition of the variable.
Variable Declaration: It mainly declares the type and name of the variable to the program.
Static modifier: static int A. The variable scope is limited to one source file and invisible to other source file.
Strict rules: A variable can be defined only once, but can be declared multiple times. It must be defined or declared before using the variable. A project can have multiple source files, but only one definition of a variable can appear in all source files.
Example:
**************************************** **********************************
Int I; // Definition
Int I = 2; // Definition
Static int I; // Definition
Extern int I = 8; // Definition
Extern int I; // This is a simple declaration.
**************************************** *********************************
Question 1: What if an initial value is specified for the definition of an external variable? Most systems refuse to accept the program.
Question 2: If an external variable is defined in multiple source programs, but the initial value is not specified? Some systems may accept it, such as vc6.0
The same program cannot be compiled in VC ++.
If you want to avoid the above problems in all C language implementations, the only solution isEach external variable is defined only once..
Question 3: is the same variable name declared as different types in different files? The programmer needs to check it by himself.
To solve the above problem, we only need to accept a simple rule: each external variable is declared in only one header file, and this header file should be included where external variables are needed. In particular, the module that defines this external variable should also include this header file.
Why do the const global variables in C do not need to be assigned an initial value, but the const global variables in C ++ need to be assigned an initial value?