Get C language local variables and global variables in one article

Preface

I recently re-learned the C language, and found that a lot of knowledge was not strong enough at the previous undergraduate level. Now I re-learn and record it together. So what are local variables and what are global variables?

Local variable
  • Local variables : To put it bluntly, local variables are variables defined within the function, that is, the variables we defined before, and 90% of the places used are local variables. So what are the characteristics of local variables?
  • Features of local variables : They are only valid within the scope of the function, which means they can only be used inside the function. When the function is used up, the local variables will be released.
Global variable
  • Global variable : As the name implies, this variable can be used by any function in this file.
  • Features of global variables : Global variables occupy storage units during the entire execution of the program, rather than opening up units only when needed.

Case

int num1 = 520,num2 = 520;
void fun();
void fun()
{
    
    
	int num2;
	num1 = 666;
	num2 = 120;
	printf("In function-fun:num1 = %d num2 = %d\n",num1,num2); // num1 = 666,num2 = 120
}
int main(int argc, char *argv[]) 
{
    
    
	printf("befor-In main:num1 = %d num2 = %d\n",num1,num2); // num1 = 520,num2 = 520
	fun();
	printf("after-In main:num1 = %d,num2 = %d\n",num1,num2); // num1 = 666,num2 = 520
	return 0;
}

NOTE

  • If the external variable and the local variable have the same name in the same source file, the external variable will be "shielded" within the scope of the local variable and will not work.
  • It is recommended not to use global variables when necessary
  • Global variables will occupy storage units during the execution of the program

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/105311713