Local variables and global variables in C language

Scope of Variables
The scope of variables refers to the scope of use of variables. According to the scope of variables, variables can be divided into local variables and global variables.

Local variables
Variables defined within a function or within a compound statement are called local variables. In addition, the formal parameters of the function are also local variables.
A local variable can only be used in the function or compound statement where it is defined, and the local variable cannot be used after leaving the function or compound statement where it is located.

· Variables defined in the main() function cannot be used in the rest of the functions.
Variables defined in a compound statement can only be used in the compound statement
Variables defined in the for() loop can only be used in the loop statement

Important Note

Local variables are created automatically when the function or compound statement is executed, and will be released automatically after the function or compound statement is executed. Therefore, defining local variables with the same name in different functions or compound statements will not interfere with each other.

global variable

Global variables are declared outside of all functions and can be used by all functions.

#include <iostream>
using namespace std;

int a=3,b=5;//定义了全局变量a,b

int fun(int a,int b)//函数形参也是a,b
{
    return a>b?a:b;
}

int main()
{
    int a=8;//在main()中定义了局部变量a
    cout<<fun(a,b);//输出a,b中的最大值
    return 0;
}
//运行结果
8

Global variables a and b are defined in the above code, and local variable a is defined in main(), which is allowed. Moreover, the fun() function is called in main(), and the actual parameters are a and the global variable b defined in main(). Note that fun() is called in main(), and its parameter is main() The a in is not a global variable a. So actually the value of the passed parameter is fun(8,5), not fun(3,5).
The system stipulates that when a local variable has the same name as a global variable, in the function or compound statement, the local variable takes precedence over the global variable , that is, the "local variable precedence" principle.
In this case, that is, when there is a variable with the same name as the global variable in the function or compound statement, when you want to use the global variable, you need to add the scope operator "::" before the variable.

#include <iostream>
using namespace std;

int a=3;//定义了全局变量a

int main()
{
    int a=8;//在main()中定义了局部变量a
    cout<<::a;//输出全局变量a
    return 0;
}
//运行结果
3

Guess you like

Origin blog.csdn.net/butnotif/article/details/128992365