C++ variable scope
Scope is an area of the program. Generally speaking, there are three places where variables can be declared:
Variables declared inside a function or a code block, called local variables.
Variables declared in the definition of function parameters are called formal parameters.
Variables declared outside all functions are called global variables.
We will learn what functions and parameters are in subsequent chapters. In this chapter, we first explain the declaration of local variables and global variables.
Local variables
Variables declared inside a function or a code block are called local variables. They can only be used by statements inside functions or code blocks. The following example uses local variables:
#include <iostream> using namespace std; int main () { // 局部变量声明 int a, b; int c; // 实际初始化 a = 10; b = 20; c = a + b; cout << c; return 0; }
Global variables
Variables defined outside all functions (usually at the head of the program) are called global variables. The value of global variables is valid throughout the life cycle of the program.
Global variables can be accessed by any function. In other words, once a global variable is declared, it is available throughout the entire program. The following example uses global variables and local variables:
#include <iostream> using namespace std; // 全局变量声明 int g; int main () { // 局部变量声明 int a, b; // 实际初始化 a = 10; b = 20; g = a + b; cout << g; return 0; }
In the program, the names of local variables and global variables can be the same, but within the function, the value of the local variable will overwrite the value of the global variable. The following is an example:
#include <iostream> using namespace std; // 全局变量声明 int g = 20; int main () { // 局部变量声明 int g = 10; cout << g; return 0; }
When the above code is compiled and executed, it will produce the following results:
10
Initialize local variables and global variables
When local variables When defined, the system does not initialize it, you must initialize it yourself. When defining a global variable, the system will automatically initialize it to the following value:
Data type | Initialization default value |
---|---|
int | 0 |
char | '\0' |
float | 0 |
double | 0 |
pointer | NULL |
It is a good programming habit to initialize variables correctly, otherwise sometimes the program may produce unexpected results.