Article Directory
1. Classification of variables
1.1 Local variables
Also called temporary variables, defined in functions and code blocks, and generally only variables that can be used inside code blocks.
1.2 Global variables
Placed outside the function (main function is also a function), a variable that can be used anywhere in the same ___.c file.
1.3 Knowledge points
1.3.1 The principle of proximity
Local variables and global variables have the same name -> the principle of proximity.
If the global variable and the local variable have the same name, the variable close to the place of use is preferred.
(It is not recommended to use the variable with the same name)
#include <stdio.h>
int global = 2020;//全局变量
int main()
{
int local = 2021;//局部变量
int global = 2022;//局部变量
printf("global = %d\n", global);
return 0;
}
1.3.2 Access Rules
Global variables can be directly accessed in any function, while local variables can only be accessed in this function.
#include <stdio.h>
double weight = 45.5;//全局变量
void fun()
{
printf("%f\n", weight);
printf("%f\n", high);//error!
}
int main()
{
double high = 180.5;//局部变量
printf("%f\n", weight);
printf("%f\n", high);
fun();
return 0;
}
1.3.3 Valid range
Variables in C language are only valid in the areas where the variables are defined and later (similar to macros).
#include <stdio.h>
int main()
{
printf("%f\n", weight);//error!
}
return 0;
}
double weight = 45.5;
2. Use of variables
(1) Variables are defined before use.
(2) Pay attention to the input and output format control, and remember to add & in scanf.
#include <stdio.h>
int main()
{
int num1 = 0;
int num2 = 0;
int sum = 0;
printf("输入两个操作数:>");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("sum = %d\n", sum);
return 0;
}
3. The scope and life cycle of variables
3.1 Scope
Refers to the effective range of variables.
3.1.1 The scope of local variables
Is the local scope of the variable.
3.1.2 The scope of global variables
It's the whole project.
3.2 Life cycle
Refers to the time period between the creation of the variable and the destruction of the variable (that is, the existence time of the variable).
3.2.1 The life cycle of local variables
It is the beginning of the entering scope life cycle and the end of the out scope life cycle.
This variable is released when the function is called.
(Formed with the call of the function, and released with the release of the function.)
3.2.2 The life cycle of global variables
It is the life cycle of the entire program.
After the program runs, it will exist until the program exits.
(Exist with the existence of the program, and release with the end of the program.)