local variables and global variables in c language

Each variable has its scope , that is, the scope in which these variables are valid;  we can divide variables into local variables and global variables according to the scope of variables ;

local variable

Local variables appear in three places:

(1) Variables defined at the beginning of a function
(2) Variables defined within a compound statement within a function
(3) Formal parameters

Variables defined inside a function are only valid within the scope of this function, that is, they can only be referenced within this function, and these variables cannot be used outside this function;

The variables defined in the compound statement can only be valid within the scope of the compound statement, they can be referenced only in the compound statement, and cannot be used outside the compound statement;

There is also the formal parameter of the function, which is only valid within the function;

The variables that appear in these three cases are local variables , see the following example:

int fun(int x,int y)
{ int sum;
sum=x+y;
}

In this example, the variable sum is defined at the beginning of the function, so it is a local variable, and its scope is this function. When it exits this function, it will be automatically destroyed and cannot be referenced elsewhere; at the same time, variables x and y are used as formal parameters is also a local variable;

Look at the following example:

int main()
{ int m,n,sum;
return 0;
}

The three variables mn max defined in the main function are all local variables, and their scope is the main function, which is not valid in the entire file or project because it is defined in the main function, and the main function cannot use other functions Variables defined in;

Consider the following compound statement:

 The c defined in line 8 is only valid in the compound statement, and it will be invalid after the statement is out. The system will release the memory unit it occupies, so the printing of line 11 will report an error, showing that the variable c is not defined in main;

global variable

A source file can contain several functions, and variables defined outside the function are global variables or external variables ; global variables are shared by all functions in the source file, and its scope of action is from the position where the variable is defined to the end of the source file ; See the following example:

Special instructions are required:

  • Global variables occupy memory units during the entire execution of the program, instead of opening storage units only when they are used;
  • The purpose of setting global variables is to increase the channel of data connection between functions. Since all functions in the same source file can refer to global variables, changing the value of global variables in any function will affect the global variables in other functions. The value of the variable , that is to say, the same global variable in all functions occupies the same block address;
  • In order to distinguish between local variables and global variables, the first letter of the global variable is usually capitalized;

Consider the following example of a global variable:

The global variable a is defined on line 2, and then the local variable a is defined on line 6. The scope of the global variable is the entire file, and the scope of the local variable a is from line 6 to line 8. In In the reference in line 7, the value of a will be the value of the local variable, that is to say, when the local variable has the same name as the global variable, the value of the local variable will overwrite the value of the global variable , so the printed result is as follows:

 It is recommended not to use global variables except when necessary, for the following reasons:

Global variables occupy middle memory units during the entire execution process, which will reduce the versatility of the function. If you move a function to another file, you need to consider moving the relevant global variables and their values ​​together, and Problems arise when the global variable has the same name as variables in other files, which reduces the reliability and versatility of the program;

Variable storage and life cycle

From the above, from the perspective of variable scope, variables can be divided into global variables and local variables; from another perspective, that is, from the perspective of the existence of variable values, some variables exist during the entire running of the program , and some variables are temporarily allocated storage units when the function they are in is called, and the storage unit is released immediately after the function call ends, and the variable does not exist;

In other words, there are two storage methods for variables: static storage and dynamic storage ;

The so-called static storage refers to the way that the system allocates fixed storage space during the running of the program, while the dynamic storage refers to the way of dynamically allocating storage space according to the needs during the running of the program;

Let’s first look at the storage space for users in the memory, which can be divided into three parts:

1) Program area

2) Static storage area

3) Dynamic storage area

Data is stored in static and dynamic storage areas respectively; for global variables, they are all stored in static storage areas, which occupy fixed storage units during program execution and will not be dynamically allocated and released; and the dynamic storage area stores the following data:

1) Function formal parameters, allocate storage space to the formal parameters when calling the function

2) There are no variables declared with the keyword static in the function, that is, automatic variables

3) Field protection and return address when function is called

For the above data, allocate dynamic storage space at the beginning of the function call, and release these spaces at the end of the function;

In C language, each variable and function has two attributes: data type and data storage category ; we are more familiar with data type, and storage category refers to the storage method of data in memory, such as dynamic storage and static storage;

There are four types of storage in C language: automatic (auto), static (static), register (extern), external (extern); according to the storage category of the variable, the scope and lifetime of the variable can be known;

storage class for local variables

 1. Automatic variable (auto)

 If the local variables in the function are not specifically declared as static storage type, the storage space is allocated dynamically, and the data is stored in the dynamic storage area;

int f(int a)  //定义函数f,a为形参
{
    auto int b, c = 3;// b c 为自动变量
    ...
}

In fact, the keyword auto can be omitted. If auto is not written, it will default to the automatic storage category, which belongs to the dynamic storage method;

2. Static local variables (static local variables)

Sometimes it is hoped that the value of the local variable in the function will not disappear after the function call ends, but will continue to be maintained, that is, the storage unit it occupies remains unchanged, and the variable has a value when the function is called next time (that is, the value at the end of the last function call ), then the local variable should be designated as a static local variable and declared with the keyword static

#include <stdio.h>

int main(void)
{
	int f(int);//函数声明
	int a = 2, i;//自动局部变量
	for(i = 0; i < 3; i++)
	{
		printf("%d\n", f(a));
	}
}

int f(int a)
{
	int b = 0;
	static int c = 3;//静态局部变量
	b = b + 1;
	c = c + 1;
	return(a + b + c);
}

 The result of the operation is as follows:

Notice: 

 1) Static local variables belong to the static storage category, and memory units are allocated in the static storage area, and are not released during the entire program running;

2) For static local variables, the initial value is assigned at compile time, and the initial value is only assigned once. It already has an initial value when the program is running, and the initial value will not be reassigned every time the function is called in the future, but the last function will be retained. The value that ends after the call; for automatic variables, its initial value is assigned when the function is called, not at compile time, so the above b= 0 statement will be executed every time the function is called;

3) If no initial value is assigned when defining local variables, for static local variables, the initial value 0 (for numeric variables) or the null character '\0' (for character variables) is automatically assigned at compile time; while for automatic For variables, its value is an indeterminate value;

4) Although the static local variable still exists after the function call ends, other functions cannot refer to it, because it is still a local variable after all, and its scope is limited to this function;

5) Since static local variables occupy memory for a long time and reduce the readability of the program, use them with caution;

3. Register variables (register variables)

In general, the values ​​of variables (including static storage and dynamic storage) are stored in the memory. When the value of a variable is used by the program, the controller sends an instruction to send the value of the variable in the memory to the calculation Then send the calculation results to the memory for storage; but if some variables are frequently used (such as 10,000 cycles, each cycle must refer to a local variable), in order to reduce the cost of accessing variables, you can Store the value of the local variable in the register of the CPU, and directly take it out of the register to participate in the calculation when necessary. At this time, this kind of variable is called a register variable, and is declared with the keyword register , as follows:

register int f;

As the speed of computers is getting faster and faster, the optimized compilation system can identify frequently used variables and automatically store these variables in registers, so it is actually not necessary to declare variables with register;

storage class for global variables

Global variables are stored in the static storage area, so their life cycle is fixed and exist throughout the running process of the program; but for global variables, there is another problem that needs to be determined, that is, its scope;

Generally speaking, an external variable is a global variable defined outside a function, and its scope is from the definition of the variable to the end of the program file; within this scope, the global variable can be referenced by each function in the program, but sometimes Programmers want to expand the scope of external variables, there are the following situations:

1. Extend the scope of external variables within a file

If the external variable is not defined at the beginning of the file, its scope is limited to the definition out to the file; if for some consideration, the function before the definition point needs to refer to the external variable, you can use the keyword extern before the reference. This variable is used as an "external variable declaration", which means that the scope of the external variable is extended to this position; as follows:

#include <stdio.h>

int main(void)
{
	int max(void);//函数声明
	extern int A, B, C;//把外部变量A B C的作用域扩展到此处
	printf("请输入三个整数: ");
	scanf("%d %d %d", &A, &B, &C);
	printf("max = %d\n", max());
	return 0;
}

int A, B, C; //定义外部变量A B C
int max(void)
{
	int m;
	m = A>B? A:B;//引用外部变量
	if(C > m) m = C;
	return(m);
}

The result is as follows:

 2. Extend the scope of external variables to other files

If a C program consists of multiple source program files, how should one file refer to an external variable already defined in another file? Take the following example:

If a C program includes two files, the same external variable NUM needs to be used in both files. At this time, an external variable NUM cannot be defined in each of the two files, otherwise there will be repeated definitions when the program is linked. The correct approach is: define the external variable NUM in any file, and use extern to make an "external variable declaration" for NUM in another file, that is, extern NUM; so that the system will know NUM when compiling and linking There are external links, you can find the defined NUM elsewhere, and then expand the scope of NUM; see the following example:

 extern can not only expand the scope of external variables in this file, but also make the scope of external variables extend from one file to other files, so how does the system handle it? In fact, when extern is encountered during compilation, first look for the definition of the external variable in this file, if not found, look for the definition of the external variable from other files, and if found, extend its scope to this file;

3. Limit the scope of external variables to this file

Sometimes it is hoped that some external variables can only be referenced in this file and cannot be referenced by other files. At this time, you can add a static declaration when defining the external variable , as follows:

After adding static, this kind of external variable is called static external variable; in the above example, the global variable A is defined in file1, but it uses static declaration, so it can only be applied to this file;

 

Guess you like

Origin blog.csdn.net/bleauchat/article/details/119429254