The best C ++ variable scope Tutorial In 2024, In this tutorial you can learn Local variables,Global Variables,Initialize local and global variables,
Scope is a regional program, in general, there are three places you can declare variables:
We will learn in later chapters what is the function and parameters. In this chapter we first explain to declare a local and global variables.
Function or variable declared inside a block of code, called local variables. They can only be used inside a function or block of code inside the statement. 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; }
In all the variables defined outside the function (usually the head of the program), known as global variables. The value of a global variable over the entire life cycle of the program are valid.
Global variables can be accessed by any function. In other words, global variable once declared throughout the program are available. The following example uses global 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, local variables and global variables can be the same, but inside a function, local variables will override the value of a global variable. Here 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 produces the following results:
10
When a local variable is defined, the system does not initialize, you must initialize it yourself. When you define global variables are automatically initialized to the following values:
数据类型 | 初始化默认值 |
---|---|
int | 0 |
char | '\0' |
float | 0 |
double | 0 |
pointer | NULL |
Properly initialized variable is a good programming practice, otherwise the program may sometimes produce unexpected results.