The difference between a variable definition and a declaration is explained in detail

  • 2020-04-02 01:44:59
  • OfStack

In programming, we always use the definition of variables and variable declarations, but sometimes we are not very clear about this concept, know how it is used, but I do not know how it is a matter of time, the following I simply introduce their differences as follows:

Variables can be declared in two ways:
(1) one is the need to establish a storage space (definition, declaration). For example, int a is stored when declared.

(2) the other is one that does not require the creation of a storage space. For example: extern int a where the variable a is defined in another file.

The former is a "defining declaration" or "definition ", while the latter is a" referncing declaration ". In a broad sense, declarations contain definitions, but not all declarations are definitions. For example, int a is both a declaration and a definition. For extern a, however, it is a declaration, not a definition. In general, we often say that the declaration of creating space is called a "definition" and the declaration of not having to create storage space is called a "declaration". It is clear that what we are referring to here is a narrow declaration, that is, a declaration of an undefined nature.

For example: in the main function


int main()
{
extern int A; //This is A declaration, not A definition, that A is an external variable that has been defined
  //Note: you can remove the type of an external variable when declaring it: extern A;
dosth();  //Executive function
}
int A;//Is the definition of the external variable (global variable) that defines A as an integer.

External variables (global) "definition" and "statement" of an external variable is not the same, the definition of external variables can only once, its location is outside of all functions, and the external variable declarations in the same file can be many times, it can within a function (which function to use in the function declaration) can also be outside of the function (before the definition of external variables point). The system allocates storage based on the definition of the external variable, not the declaration of the external variable. For external variables, initialization can only take place in the definition, not in the declaration. The purpose of a declaration is to declare that the variable is an external variable that has been defined later and is merely a declaration to refer to the variable "in advance." Extern is declared, not defined.

Declaring a variable as static does two things:
(1) if a local variable is declared as static, the space allocated for the variable will always exist in the entire execution period of the program
(2) the external variable is declared as static, so the function of the variable is limited to the module of this file


Related articles: