Storage types: auto, static, extern, and register

Source: Internet
Author: User

The attributes of variables and functions include the data type and data storage class. The storage class index data is stored in memory (static and dynamic), including auto, static, register, and extern.

 

Memory. Specifically, memory is divided into three parts: static zone, heap zone, and stack zone. External variables and global variables are stored in the static zone, local variables are stored in the stack zone, and the dynamically opened memory exists in the heap zone.

 

I. Comparison between simplified and simplified

ExternThe external variable Declaration refers to an object that has been defined elsewhere. It is only a duplicate reference to the variable and will not generate new variables.
StaticStatic data is stored in the global data zone, but the scope is only in this file/function. Therefore, you can declare static variables with the same name in two different files/functions, but they are two different global variables. If it is defined in a function, the object has no link and cannot be accessed outside the function. If it is defined outside the function, the object has an internal link, and other program files cannot access it.
AutoCommon Local stack variables are automatically stored, and such objects are automatically created and destroyed. We recommend that you place these variables on the stack, allocate memory when calling the function, and release memory when the function ends. Generally, auto is automatically stored by default. Most of the variables in our programs are automatic variables.
RegisterRegister variable, requesting the compiler to save this variable in the CPU register to speed up program operation.

The system registers are restricted. When declaring variables, such as register int I., this storage type can be used for frequently used variables.

Ii. Additional Notes

1. variables of the auto storage type can only be used within a certain program range. They use the stack method to allocate space.

Auto can be omitted when defining variables, such as: auto int I; equivalent to int I.

2. Global variables cannot be declared as auto variables. Register is not applicable to global variables.

3. Register cannot be accessed. For example, int I; (Auto automatically) int * P = & I; is correct, but register Int J; int * P = & J; is wrong, because the address of the register cannot be set.

4. Declare a variable as register. The Compiler does not necessarily process it as a register variable. After all, resources are limited.

5. In fact, the general compilers ignore auto and register declarations. The current compiler can distinguish the variables that are best placed in registers and those in the stack; even some variables are sometimes stored in the stack and sometimes in registers.

6. Auto register is used to modify variables. All static extern functions can

Iii. Details

 

From the perspective of variable value existence time (lifetime): static storage mode and dynamic storage mode.

From the perspective of the scope (Space) of a variable: global variables and local variables.

Bucket in user zone:

| Program area |

| Static storage area |

| Dynamic storage |

During the static storage mode, the system allocates a fixed storage space, and the dynamic storage mode dynamically allocates the storage space as needed. Global variables are stored in static storage areas. Dynamic storage areas mainly include: function parameters, storage space allocation during function calls; automatic variables (local variables without static Declaration ); field Protection and return address during function calling.

Auto auto variables:Generally, auto is automatically stored by default. Most of the variables in our programs are automatic variables.

Static variable::The local variable declared in static state does not release the bucket after the function call ends. When the function is called again, the variable has a value. Other functions cannot be referenced. When static local variables are compiled, the initial values are assigned. If the local variable does not assign an initial value, the static variable is automatically assigned a value of 0 or an empty character. The initial values of automatic variables are uncertain. It is best not to use it directly. If the value of the last call needs to be retained in the function or the variable is referenced but not changed after initialization, you can use static local variables to consume memory.

 

Register variable:Both dynamic and static variables are stored in the memory. When this value is encountered in the program, the controller sends a command to send the value of the variable to the memory, and the number of variables needs to be saved to the memory. If a variable is frequently used, for example, the local variable is referenced in multiple cycles in a function every time, we can put the value of the local variable into the CPU register, called the register variable. It does not need to be accessed in memory multiple times to improve efficiency. However, only local automatic variables and form parameters can be used as register variables. Some registers are used for function calling and are released when the function ends. Different systems have different requirements for register, such as limits on the number of defined register variables and data types. Some default rules are automatic variable processing. So it is generally not used in the program.

Extern external variable: if we want this external variable to be used only in this file, but cannot be referenced by other files, we can add static declaration when defining the external variable. Prevent misuse of modules written by others. For a global variable defined outside the function, the scope begins with the variable definition and ends with the end of the program file. We can use extern to declare an external variable to extend its scope. In the same file, after the extern declaration, the scope can be extended to the declaration to the end of the file. For example, if an external variable A is defined after a function, the subsequent function can use this variable, but the previous function cannot use this variable. You can use extern to solve this problem. Multiple files can be used by making an extern declaration in the file where the external variable is not defined. Note that the value of the global variable may be changed when a file is executed, affecting the calling of other files. If extern is encountered during compilation, the system first checks whether the external variable is defined in the file. If not found, find the link in other files.

Iv. Example

1. extern:

 

All objects of extern have a static lifecycle. When using extern, note that the definition cannot be repeated; otherwise, an error is reported during compilation, such as: program file 1: extern int A = 10; // compilation warning. It is best not to initialize the variables of extern in program file 2: extern int A = 20; // repeated definition, should be changed to extern int;

 

 

In general, it is best to remove the extern modifier (but do not define it repeatedly) If Initialization is required. In addition, if other program files also need to use this variable, extern can be used to declare the variable.

2.

1. Local variables: they are also called automatic variables. They are declared at the beginning of the function and survive in the stack. Their life ends with the function returning.
# Include <stdio. h>IntMain (Void) {AutoIntI = 9;/* the keyword for declaring a local variable is auto. Because it can be omitted, almost no one uses */printf ("% d \ n", I); getchar ();Return0 ;}

2. Global variables: declared in the external body of the function, generally before the function; each function can use it, but the global variables should be used as little as possible.
# Include <stdio. h>VoidAdd (Void);VoidMul (Void);IntGI = 3;/* global variable */IntMain (Void) {Printf ("% d \ n", Gi);/* 3 */Add (); printf ("% d \ n", Gi ); /* 5 */MUL (); printf ("% d \ n", Gi);/* 10 */getchar ();Return0 ;}VoidAdd (Void) {Gi + = 2 ;}VoidMul (Void) {Gi * = 2 ;}
The global variable is initialized as null, and the local variable is a junk value before being assigned a value:
# Include <stdio. h>IntGI;/* global variable */IntMain (Void){IntI;/* handle variable */printf ("% d, % d \ n", GI, I); getchar ();Return0 ;}

When the global variable and the local variable are renamed, the local variable is used:

#include <stdio.h>int a = 111, b = 222;int main(void){    int a = 123;    printf("%d,%d\n", a, b); /* 123,222*/    getchar();        return 0;}

3. static Keyword: the modified local variable is a static local variable. The static local variable is saved as a global variable. The difference is that it only belongs to the function that owns it. It will also be initialized as null.

# Include <stdio. h>VoidFun1 (Void);VoidFun2 (Void);IntMain (Void){IntI;For(I = 0; I <10; I ++) fun1 (); printf ("--- \ n ");For(I = 0; I <10; I ++) fun2 (); getchar ();Return0 ;}VoidFun1 (Void){IntN = 0;/* General local variable */printf ("% d \ n", N ++ );}VoidFun2 (Void){Static IntN;/* Static local variable; will be initialized to null */printf ("% d \ n", N ++ );}
 

The global variable modified with the static keyword is a static global variable. The static global variable can only be used to define its unit.

// For example, defined in file1.c:Static IntNum = 99;/* remove other static units before using * // use in file2.c: # include <stdio. h>Extern IntNum;IntMain (Void) {Printf ("% d \ n", num); getchar ();Return0 ;}
[CPP]View plaincopy

  1. <PRE> <span style = "font-family: Arial, Helvetica, sans-serif; white-space: normal; Background-color: RGB (255,255,255)">
  2. </Span> </PRE> <span style = "font-family: Arial, Helvetica, sans-serif; white-space: normal; Background-color: RGB (255,255,255) "> use static variables to record the number of times a function is called: </span> </PRE> <span style =" font-family: Arial, Helvetica, sans-serif; white-space: normal; Background-color: RGB (255,255,255) ">
  3. </Span> </PRE>
#include <stdio.h>
IntFun (Void);IntMain (Void){IntI;For(I = 0; I <10; I ++) {printf ("the function has been called % 2D times; \ n", fun () ;}getchar ();Return0 ;}IntFun (Void){Static IntN;Return+ + N ;}
 

4. register variable (Register): The register variable will try to put the variable into the register (instead of the stack or heap) to speed up access.

# Include <stdio. h> # include <time. h> # define time 1000000000IntM, n = time;/* global variable */IntMain (Void) {Time_t start, stop;Register IntA, B = time;/* register variable */IntX, Y = time;/* general variable */time (& START );For(A = 0; A <B; A ++); time (& stop); printf ("register variable time: % d seconds \ n", stop-start ); time (& START );For(X = 0; x <Y; X ++); time (& stop); printf ("general variable time: % d seconds \ n", stop-start ); time (& START );For(M = 0; m <n; m ++); time (& stop); printf ("global variable time: % d seconds \ n", stop-start ); getchar ();Return0 ;}
[CPP]View plaincopy

  1. <PRE> </PRE>

4. extern Keyword:
Use extern to declare the external global variables;
If extern is not used, it will be redefined;
In the connection phase, global variables of different units in the same program are shared, so they cannot be redefined;
In this example, the variable is placed at the end of the file to avoid having to involve another file.

In addition, extern is mainly used for functions.

#include <stdio.h>extern int g1;int main(void){        extern int g2;    printf("%d,%d\n", g1,g2);      getchar();    return 0;}int g1 = 77;int g2 = 88;
5. Volatile Keyword: when a program uses a variable, especially when it uses the variable for multiple consecutive times, it generally loads the register, directly accesses the variable from the Register, and then returns it back to the memory;
But what if the returned memory value of this variable has changed (Modified from outside?
To avoid this situation, you can use volatile to describe the variable to ensure that each usage of the variable is directly accessed from the memory.
However, this will definitely affect the efficiency. Fortunately, it is not commonly used.

In addition, if const volatile is used at the same time, this variable only accepts external modifications.

#include <stdio.h>volatile int num = 123;int main(void){        printf("%d\n", num);    getchar();    return 0;}
6. Restrict Keyword: Restrict is somewhat different from volatile. However, restrict is only for pointers.
It seems that C ++ builder 2009 does not support it and cannot be tested for the moment. Original address: http://blog.csdn.net/firefly_2002/article/details/7940802

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.