C language - Basics - study notes (8): function variables (auto, static, register, extern)

C language - Basics - study notes (8): function of variables

I. lifetime and scope

All variables in C programs have a certain life span and a scope. Survival means the program is running, variables occupy the memory of time. Scope variable is the effective area of ​​the code is used in the program.

1. The lifetime of a variable

Survival period is the period of memory variables occupy the entire program is running. When the program runs to the variable definition statement, the compiler memory is allocated, which is its beginning, when a variable amount of memory to be released, compared with the end of the lifetime.

Example 1

#include <stdio.h>

int reverse(int a){
	return -a;
}

int square(int b){
	return b*b;
}

int main(void){
	int key = 1;//key的生存期开始
	printf("%d\n",reverse(key));
	printf("%d\n",square(key));
	//key的生存期结束
	return 0;
}

2. The scope of variables

Scope refers to the code area code may be used. The use of variable-scope variable is an illegal operation.

{	//程序块A开始
	int m = 2;
	{	//程序块B开始
		int n = 3;
		m = 9;
	}	//程序块B结束
	{	//程序块C开始
		n = 7;
		++m;
	}	//程序块C结束
	printf("m=%d,n=%d\n",m,n);
}	//程序块A结束

An upper block for the block A and block B block C of
block B and block C of each other outside the block, and the block is the lower block A is
variable m A block internal variable of the program external variables block B and block C,
variable n B block is an internal variable and a program block, block C for the external variables

A variable m is defined in the block may be used in this application layer can be used in the lower block B, may be used in a lower layer block C but variable internal block B n of the block only in B is used.

II. Local and global variables

1. Local variables

Local variables are scoped variables can not cover the entire area of the code. Local variables can not exceed the scope of the function thereof belongs.
As a temporary variable, the main advantage of local variables is required only when the editor will assign memory.
Shape parameter is a function of local variables in the function.

Example 2

#include <stdio.h>
void print_value(void){
	int var = 1;

	++var;
	printf("var=[%d]\n",var);
}

int main(void){
	printf("Call print_value() at first time:\n");
	print_value();

	printf("Call print_value() at second time:\n");
	print_value();
	/*在这里使用var变量是错误的
	++var;
	*/

	return 0;
}

2. Global Variables

In all external variables defined functions, namely the function of all external variables, is called "global variables."
Global variables for all public functions, and each function to change the global variable values are saved in memory.

Example 3

#include <stdio.h>

int g_var;

void print_value(void){
	++g_var;
	printf("g_var = [%x]\n",g_var);
}

int main(){
	printf("Call print_value() at first time:\n");
	print_value();

	printf("Call print_value() at second time:\n");
	print_value();

	++g_var;
	printf("g_var = [%x]\n",g_var);
}

Here Insert Picture Description

3. Initialize global variables

It is displayed if the local variable is not initialized, the compiler will not automatically cleared for; If the global variable is not explicitly initialized for the compiler it is automatically initialized to zero to clear memory space.

Example 4

#include <stdio.h>
#define SIZE 12
//定义两个全局变量
float g_arrayFloat[SIZE];
int g_valueInt;

void print_array(const float a[SIZE]){
	int i = 0;

	for(i = 0;i<SIZE;i++){
		if(SIZE/2 == i)
			printf("\n\t");
		printf("%2.2f\t",a[i]);
	}
	printf("\n");
}

int main(void){
	//定义两个局部变量
	float arrayFloat[SIZE];
	int valueInt;
	//输出全局变量的初始值
	printf("Globle variable: g_arrayFloat\n\t");
	print_array(g_arrayFloat);
	//输出局部变量的初始值
	printf("Local variable: arrayFloat\n\t");
	print_array(arrayFloat);

	printf("Globle variable: g_valueInt = %d\n",g_valueInt);
	printf("Local variable: valueInt = %d\n",valueInt);

	return 0;
}

Here Insert Picture Description
If the variable in the entire process needs to be used, it is recommended to set a global variable, so that the scope covering the entire program; if only needs to use the variable in a certain small, it is recommended that the definition of local variables block, so that only the scope of this block, so that after completion of this subroutine block execution memory variables released.

When the variable name can use the same variable names in different functions, interference between each other. However, when the present block and the upper layer block, or variable name and the lower layer of the block overlap, naming conflicts occur. Variable with the same name will be high-level block mask underlying variable block of the same name.

The same name but different types of variables are variables of the same name.

Example 5

#include <stdio.h>

int max = 14;//定义全局变量

int call_max(const int a,const int b){
	int max = a;

	if(a < b)
		max = b;

	printf("In call_max():\n");
	printf("\t&max = [%p]\n",&max);
	printf("\t&a = [%p]\n",&a);
	printf("\t&b = [%p]\n",&b);

	return max;
}

void print_max(void){	//没有重新定义max
	printf("In print_max():\n");
	printf("\tmax = [%d]\n",max);
	printf("\t&max = [%p]\n",&max);
}

void increase_max(void){	//没有重新定义max
	++max;  //当没有重新定义max时,max就是全局变量的max

	printf("In increase_max():\n");
	printf("\tmax = [%d]\n",max);
	printf("\t&max = [%p]\n",&max);
}

int main(void){ //main中的变量a和b与call_max中的a.b互为外部函数,分别有各自的地址,互不相关
	const int a = 7;
	const int b = 2;
	int max = 0;

	max = call_max(a,b);

	printf("In main():\n");
	printf("\t&max = [%p]\n",&max);	
	printf("\t&a = [%p]\n",&a);
	printf("\tb& = [%p]\n",&b);

	print_max();
	increase_max();

	return 0;
}

Here Insert Picture Description

4. Comparison of local variables and global variables:

1, and there is no definition of the initialization, the value of the local variable is random, and the default values of global variables to 0.
2, the upper range: global variables have file scope, local variables only the code block scope.
3, the life cycle: Global variables are born in the initialization phase before the program starts running, the entire program ends quit when it died; and local variables born when entering the code block where a local variable in the code block exit the time of death.
4, dispensing position variables: global variables are allocated in the data segment, while local variables allocated on the stack.

Analyzing a variable can not be used, there is no definition, we must pay attention to two things: first, whether the variable defined in the scope of the currently valid, contains the current position; the second, the use of the variable must be defined. So be sure to reference variables in the variable definition before

Basic Concepts:
Scope: The work area is the scope of work.
Block: the so-called code blocks, is enclosed by {} piece of code.
Data group: the number of the data segment is stored as a global variable that is present in the data segment
of code segments: program code is stored, typically is read-only.
Stack (stack): last out. C language local variables allocated on the stack.

III. Storage class variables

C language variable has two attributes: data type and storage class.
C language defines four key modifier storage class as a variable, namely: Auto, static, the Register and extern.
Storage class variable determines the variable storage area in memory.

1. Memory storage area

1. Stack
The stack is a dynamic compiler manages a storage area for storing temporary variables, i.e., memory is allocated only when needed, the compiler will automatically recover when not needed. (Function parameter, local variables, other temporary variables)
2. heap
memory is a dynamic memory heap area management programs for distribution and use by the application program malloc function required by the program itself is released.
3. static storage area
of memory for storing a static global variable storage region, that area of memory had been allocated at the fixed start of the program until the program is automatically released by the compiler, in the region are allocated throughout the program execution It is effective.
4. Constant memory area
Constant Constant memory area for storing the program, while the constant const optimized by the compiler may also occupy this region of memory.

2.auto variable

The role of storage class auto variables are declared survival of automatic type, memory auto variables are automatically allocated by the compiler from the stack, so the auto variable is a temporary variable .
auto data type variable name;
Data type auto variable name;
Declare all local variables if the free storage class, default to auto variables.

const auto int amount = 1;

You can not function declared outside auto variables.

Examples 6

#include <stdio.h>

auto int key;

int main(void){
	printf("key = %d\n",key);
	return 0;
}

Here the key variable is declared as auto variables, and because the variable definitions exist outside the function, and therefore is a global variable, conflict.

3.static variable

Memory class variables are allocated from the rest area, the survival of the entire process for the implementation of the program. static local variables can be modified global variables can be modified.
static data type name variable name

Because auto local variables within the function will be released after the end of each function, so this information can not be reserved function calls. However, when the function function need to pass information in multiple calls, you need a variable can retain memory without releasing at the end of the function, which is used in a static variable.

Examples 7

#include <stdio.h>

int countA(void){
	static int n = 0;
	++n;
	return n;
}

int countB(void){
	auto int n = 0;
	++n;
	return n;
}

int main(void){
	printf("Call countA():%d\n",countA());
	printf("Call countA():%d\n",countA());
	printf("Call countA():%d\n",countA());

	printf("\nCall countB():%d\n",countB());
	printf("Call countB():%d\n",countB());
	printf("Call countB():%d\n",countB());

	return 0;
}

Here Insert Picture Description
This example illustrates: auto local variables, which is allocated on the stack memory, the end of each function will be released. static variables static variables, static memory allocation from the memory area, the information will be retained at the end of the function.

The keyword static can also be used to declare global variables, whose role is to limit the variables used in this document. static global variables in different file with the same name can be also modified the same name with no static global variables.

Definition statement static local variable is performed only at the first call.

Summary:
1, static local variables and local variables different from the ordinary. Static local variable is defined within the function of static local variables defined above to add static keyword to identify the function of static local variable is located in a multi-called multiple times, only the first and only experience variable definition initialization that in the future times longer defined and initialized when you call, but to maintain the value of the execution time of the last call before this variable. This is then used.
2, create a static local variable in the first function is called and initialized when the function exits but it is not dead, but retains its value to wait for the next time it is called function. Next time will not re-create and initialize the variable when you call, but directly with the last remaining value basis to operate.
3, this feature static local variables, and global variables are very similar. The same point is they have created and initialized once, after calling a time when the last remains unchanged. The difference is that different scopes.

4.register variable

When accessing a program variable, the value of the variable from memory into a register extract; after operation, if the value of the variable is changed, the need to re-register the value returned to the memory storage.
Type of stored value of the variable register will be stored in the register request directly. register variables typically define the variables used in the program frequently used , can improve efficiency.
register data type name variable name

register only modifies the function of the variables, including local variables and parameters form.

void function(register int x,register int y){
	register int a = 1;
}

A storage variable can only be declared a category.

5.extern variable

To use a variable before the variable definition, you can make use of extern declared.
extern is to expand the role of global variables in a file scope. You can also make global variables scope extended to other files.

For example, a program has two files file1.c and file2.c

//file1.c
int a = 1;

//file2.c
extern int a;
void main(void){
	printf("a = %d\n",a);
	return 0;
}

file1 already defined a, if you want to use the variable in file2, you only need to use extern scope at the beginning of the expansion of a.

Exercise 1

//使用static局部变量来完成函数的函数体,要求:返回传递给该函数的所有参数的和
#include <stdio.h>

int func(const int a){
	static int sum = 0;
	sum += a;
	return sum;
}

int main(void){
	int a = 0;
	int i = 0;
	int rst = 0;

	printf("Please input 6 numbers:\n");

	for(i=0;i<6;i++){
		printf("[%d] = ",i+1);
		scanf("%d",&a);
		rst = func(a);
	}

	printf("The sum is %d.\n",rst);

	return 0;
}

Here Insert Picture Description
Exercise 2

//使用static全局变量来完成函数的函数体,要求:返回传递给该函数的所有参数的和
#include <stdio.h>

static int sum = 0;

int func(const int a){
	sum += a;
	return sum;
}

int main(void){
	int a = 0;
	int i = 0;
	int rst = 0;

	printf("Please input 6 numbers:\n");

	for(i=0;i<6;i++){
		printf("[%d] = ",i+1);
		scanf("%d",&a);
		rst = func(a);
	}

	printf("The sum is %d.\n",rst);

	return 0;
}

Here Insert Picture Description

Published 55 original articles · won praise 76 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_42826337/article/details/102811840