C ++ 2.2 variable declaration, definition, initialization, identifiers, scopes


Identifier

Is the variable naming, characters can be used: numbers, letters, underscores
variable named only by letters and underscore the beginning, there is no limit on the length, case sensitive.


Declare and define and initialize

The int a = 0;declaration and definition of variables a, 0 is initialized.


Declare and define

int a;


extern only declare variables

Use externkeywords to declare variables only. As extern int a;
just stated is not initialized


Scope

Mainly to see where the statement. If declared outside a function braces, it is the global scope; braces declared within a function, is local scope.

No extern declarations and definitions

When a global variable declarations and are defined in the source file s1; (regardless of extension, described here only for a)
the source file s2 a global variable to be used, then the need #include "s1", i.e. the introduction of s1.
If not incorporated in s2 s1, and declarations define global variables individually and a, then when the two source files are linked at compile time, occurs "duplicate definition of the error variable of the same name."


There extern statement

If a global variable declared in the source file in s1; (regardless of extension, here just for a description)
also states in s2;
this time is not defined, it is not initialized.

eg.

s1:
extern int a;

s2: 
extern int a;
int a; 

Benefits are: no need to use global variables, and the introduction of the entire source file


The default initialization of global variables and local variables

  • When a global variable is not assigned, the default can be initialized.

The type of support required variables default initialization. For built-in types are supported. Standard Template Library STL is a template class, it is also supported.

  • When a local variable is not assigned, the default will not be initialized. Direct use may lead to errors.
发布了400 篇原创文章 · 获赞 364 · 访问量 162万+

Guess you like

Origin blog.csdn.net/jjwwmlp456/article/details/89604930