Introduction to C language (14) scope and storage type of variables

Source: Internet
Author: User
Tags modifiers

Scope and storage type of variables

I. Scope and lifetime
There are three types of identifier scopes for C programs: local, Global, and file. The scope of an identifier determines which statements in the program can use it, in other words, the visibility of identifiers in other parts of the program. Typically, the scope of an identifier is implicitly described by its location in the program.
1. Local scope
The variables in the previous examples are local scopes, which are declared inside the function and cannot be accessed by the code of the other functions. The scope of the formal parameters of a function is also local, and their scope is limited to the block of statements used inside the function.
void Add (int);
Main () {int num=5;add (num);p rintf (%d\n,num);/* output 5*/}void Add (int num) {num++;p rintf (%d\n,num);/* Output 6*/}
The two num variables in the above example are local variables and are visible only in the function itself. As we said earlier, the two functions with the same name will not interfere with each other, that is the truth. So the above two outputs, in the main function is still 5, the output in the Add () function is 6.

2. Global scope
For variables with global scope, we can access them anywhere in the program. When a variable is declared outside of all functions, that is, at the beginning of the program, the variable is a global variable.
void Add (int);
int Num;main () {int n=5;add (n);p rintf (%d\n,num);/* Output 6*/}void Add (num)/* Formal parameter does not specify type */{num++;p rintf (%d\n,num);/* Output 6*/ }
The above main () and add () do not declare num, but at the end of the output it is required to output num, because at the beginning of the program it is declared that NUM is a global variable, that is, the variable can be used in all functions. At this point the value of the variable is changed in a function, and the values in the other functions are affected. The above example output is 6 because the value of NUM is changed in the Add () function, since NUM is a global variable, as if their two functions share a variable, so num in the main () function changes as well.

3. File Scope
In many C language books, there is no description of the scope of the file, or just a slight mention, in fact, the file scope in the larger program is very useful (in a multi-file system). A file scope is an external identifier that is visible only in summary functions within the same translation unit that declares it. A conversion unit is a source code file that defines these variables and functions (including any source code files that are included through the # include directive). The static storage type modifier Specifies that the variable has a file scope.
static int num;static void Add (int); main () {scanf (%d,&num); add (num) printf (%d\n,num);} void Add (num) {num++;}
The above program in the variables num and the function add () in the declaration is the static storage type modifier, which makes them have file scope, only the love definition of their files within the visible.
Since most of the programs we mention have only one compilation file, this is not really meaningful. However, there are many documents in the actual project, they are not written by one person, and are done by many people, these files are compiled by themselves, which inevitably makes some people use the same global variable name, so that in order to later in the program, the variables and functions do not interfere with each other, you can use the static modifier, This is not visible in other code files that are connected to the same program.

second, the variable storage type
As we said earlier, declaring a variable is in a similar form:
int num;
float Total;
None of them have storage type modifiers, and we can also tell the compiler what type of variables to process by storing type modifiers when declaring. There are four types of storage: Automatic (auto), Static, external (extern), register (regiser).
1. Automatic storage type
The automatic storage type modifier Specifies that a local variable is automatic, which means that each time the statement block that defines the variable is executed, a new copy is generated in memory for that variable and initialized. In fact, if not specifically indicated, the local variable storage type is automatically the default, therefore, the addition of auto can be.
Main () {auto int num=5;printf (%d\n,num);}
In this example, the execution of the code is the same regardless of whether the declaration of the variable num contains the keyword auto. The form parameter storage type of a function is also automatic by default.

2. Static storage variables
The static keyword has been used before, but for local variables, the meaning of the statically stored type is different, which is relative to the automatic storage type. The scope of a static local variable is still nearly limited to the statement block that declares it, but the variable will always hold its value during the execution of the statement block. Also, the initialization value only works if the statement block is executed for the first time. During the subsequent run, the variable retains the value of the last execution of the statement block. See the following two corresponding programs:
/*1.c*//*2.c*/
int add (); int add ();
Above two source files, only the variable declaration in the function add () is different, one is the automatic storage type, and the other is the static storage type.
for 1. c file, the output is 51 51 51; This is good to understand, each time the initial value is 50, and then add 1 up.
for 2. c file, the output is 51 52 53; This is because the variable is static, only 50 is initialized for the first time, and the last result value is used later. When the first call to add () is initialized to 50, then add 1, the output is 51, when the second call is not initialized, then the value of NUM is the last 51, then add 1, Output 52, when the third call, Num is 52, plus 1 is 53.
Comparisons will find their differences. Static variables are often used in the next SectionTo recursive function.
When the initial value of a static variable is not specified for the first time, the default is 0.

Let 's take an example to understand the static variables we're talking about.
Find the value of 1+2+......+100
void add (); int result;main () {int i;result=0;for (i=0;i<100;i++) Add ();p rintf (%d\n,result);} void Add () {static int num=0;num++;result+=num;}
The Add () function is called 100 times, and Num's values change from 11 to 100, so that they can be calculated. If you write an int num=0, that's the value of 1+1+......+1 100 1.
In fact, similar problems can be solved by recursive functions, and what is recursive is described in the next section.
3. External Storage type
An external storage type declares an external variable that the program will use, but not yet defined. Typically, an external storage type is used to declare a variable that is defined in another translation unit. For example, this example includes two files.
/*1.c*/void a (); main () {extern int num;a ();p rintf (%d\n,num);} /*2.c*/int num;void A () {num=5;}
The two programs are compiled separately and then connected to an execution file. How to do this, you can see some manuals, here I briefly said. After compiling all two files, make a. prj file with the following:
1.c
2.C
Only these two lines, this can be written in the editing state, save, named 1.prj.
Then select the Project option, select Project name, fill in the 1.PRJ filename, and press F9 to generate the 1.exe file.

The variable num in the main () function is defined in another file. Therefore, when the compiler compiles 1.c, the address of the variable cannot be determined. At this point, the external storage type declaration tells the compiler to treat all references to Num as an indeterminate reference, and then to handle the reference to the variable num when all the cheap good target code is connected to an executable module.
The declaration of an external variable can be either inside or outside the function that references it. If the variable is declared outside the function, then all functions within the same conversion unit can use the external variable. Conversely, if inside a function, then only this function can use the variable.

The problem with file scope is mentioned earlier, if the global variable is declared with the static modifier, then the variable is only visible within the current file, and extern can refer to variables in other files. So in a large program, each programmer just completes a small piece, in order to let their own variables not used by other programmers, maintain a certain degree of independence, often in front of the global variables and static. We can illustrate this by:
Or the above two files, now add a file 3.c, the content is:
static int num;void A () {num=6;}
Add 3.c to the 1.prj file so that we generate a 1.exe file that executes when the output is 5 instead of 6. Because the NUM variable of the 3.c file increases the file scope, it cannot be used in other files.
4. Register Storage Type
A variable declared as a register store type, except that the program cannot get its address, and the rest is the same as an automatic variable. As for what is the variable address, it is described in detail later when the pointer is said.
Main () {register int num;num=100;printf (%d,num);}
The purpose of using a register storage type is to have the programmer specify that a local variable is stored in a hardware register in the computer rather than in memory to increase the speed of the program. However, this only reflects the programmer's subjective will, and the compiler can ignore the Register store type modifier.
The address of the register variable cannot be obtained because the hardware registers of most computers do not occupy memory addresses. Furthermore, even if the compiler ignores the register type modifier and places the variable in the memory of the settable address, the restriction that we cannot take the address still exists.
To make efficient use of register storage types, you must understand the internal structure of the processor as assembler programmers do, know the number and kind of registers that can be used to hold variables, and how they work. However, different computers may not be the same in these details, so for a portable program, the Register storage type is not very useful. Especially now a lot of compilers can provide good optimization effect, far more effective than the programmer to choose. However, the register storage type can also provide an important reference for the optimizer.

Introduction to C language (14) scope and storage type of variables

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.