The role of the static keyword in C language, and the static keyword in C Language

Source: Internet
Author: User

The role of the static keyword in C language, and the static keyword in C Language

Functions of static keywords in C Language

Hua Qing vision 2014-10-05 Zhang junhao, Haidian District, Beijing

1. layout of executable files (elf) after C source program Compilation


1) body segment-The machine instruction part executed by the CPU; a program has only one copy; read-only to prevent the program from modifying its instruction due to accidents;

2) initialize the data segment (Data Segment)-store all the global variables assigned with the initial value in the program.

3) Non-initialized data segment (bss segment) -- no global variable is initialized in the program; the kernel initializes this segment to 0.

4) Stack-growth direction: top-down growth; automatic variables and information to be saved for each function call (Return

Address, local variable, Environment Information ).

5) Heap-dynamic storage. It is a data type that is extended to the high address, and is an extended mode from bottom to top.

 

The storage specifiers auto, register, extern, and static correspond to two storage period modes: Automatic Storage Period and static storage period. Auto and register correspond to the automatic storage period. A variable with an automatic storage period is created when it enters the block where the variable is declared. The variable exists during the block activity and is revoked when it exits the block.

The extern and static keywords are used to describe variables and functions with a static storage period. Local variables declared with static have static storage duration or static range (static extent ). Although its value remains valid between function calls, its name visibility is limited to its local domain. The static local object is initialized for the first time when the program executes the declaration of the object.

Ii. Life Cycle

(1) local variables are allocated space for each function call and destroyed after the function call is completed.

(2) global variables are allocated space when the program starts running and destroyed at the end of the program.

(3) If the names of local variables and global variables are the same, the local variables temporarily overwrite the global variables.

(4) global variables can only be initialized using constant expressions. Because the program starts to run with an appropriate value to initialize global variables, the initial values must be saved in the compiled executable file, therefore, the initial value must be calculated during compilation. The C language syntax stipulates that global variables can only be initialized using constant expressions.

 

Iii. Functions of static keywords in C Language

[1] static variables

1. static modify global variable: Add static before the global variable, and the global variable is defined as a Global static variable.

Features:

1) storage area (in-memory location): The static storage area has not changed (the static storage area exists throughout the program running );

2) initialization: uninitialized Global static variables are automatically initialized to 0 by the program. (The value of the automatic object is arbitrary unless it is displayed for initialization)

3) Scope: The Global static variable is invisible outside the file that declares it. Accurately starts from the definition to the end of the file. The scope of a non-static global variable is the entire source program (multiple source files can be used together), while a static global variable limits its scope, that is, it is valid only within the source file that defines the variable, it cannot be used in other source files of the same source program. Benefits:

1) it will not be accessed or modified by other files;

2) variables with the same name can be used in other files without conflict.

 

2. static local variable modification: add the keyword static before the local variable, and the local variable is defined as a local static variable. Features:

1) Storage zone (location in memory): changed from Stack to static storage zone rodata. The lifetime is the entire source program and can only be used within the function defining the variable. After exiting the function, although the variable still exists, it cannot be used;

2) initialization: the initial value assigned to the static local variable is performed during compilation, that is, only the initial value is assigned once, and the initial value exists when the program is running. In the future, the initial values will not be re-assigned for each function call, but the values at the end of the last function call will be retained. However, assigning an initial value to an automatic variable is not performed during compilation, but during function calling. Each call to a function returns a value, which is relative to executing a value assignment statement. If the initial value is not assigned to the local variable, the initial value 0 (For numeric variables) or null characters (For numeric variables) are automatically assigned to the static local variable during compilation ). For an automatic variable, if the initial value is not assigned, its value is uncertain. This is because the storage unit has been released after each function call, and the storage unit is re-allocated next time, and the value in the allocated unit is uncertain.

3) scope: the scope is still a local scope. When the function or statement block defining it ends, the scope ends. Although the variable still exists, it cannot be used.

 

[2] static Functions

When the keyword static is added before the return type of the function, the function is defined as a static function.

Function definitions and declarations are extern by default, but static functions are only visible in the declared files and cannot be used by other files. It can only be called by functions in this file, but not by functions in other files of the same program. Benefits:

1) functions with the same name can be defined in other files without conflict

2) static functions cannot be used by other files.

 

Iv. Differences between static variables and functions and common variables and functions

[1] differences between static variables and common variables and functions

 

1) What is the difference between static global variables and common global variables?

The description of global variables (external variables) is preceded by static to form a static global variable.

Global variables are static storage, and static global variables are also static storage. The two are not different in storage methods.

The difference between the two lies in that the scope of non-static global variables is the entire source program. When a source program is composed of multiple source files, non-static global variables are valid in each source file. The static global variable limits its scope, that is, it is valid only in the source file defining the variable, and cannot be used in other source files of the same source program. Because the scope of static global variables is limited to one source file, they can only be shared by functions in the source file. Therefore, errors in other source files can be avoided.

Static global variables are modified only once to prevent being referenced in other file units;

2) What is the difference between static local variables and common local variables?

After a local variable is changed to a static variable, its storage mode is changed, that is, its lifetime is changed. After changing a global variable to a static variable, it changes its scope and limits its scope of use.

Static local variables are initialized only once, and the next time is based on the previous result value;

[2] What are the differences between static functions and common functions?

 

Static functions have different scopes than normal functions. They are only available in this file. The function used only in the current source file should be regarded as an internal function (a static-modified function). The internal function should be described and defined in the current source file. For functions that can be used outside the current source file, it should be described in a header file that the source file to use these functions must contain this header file. the static function has only one copy in the memory, and the normal function maintains one copy in each call.

 


What is the role of static in C language?

In the C language, the literal meaning of static can easily lead us astray. In fact, it has three functions.
(1) first role: Hide.
When we compile multiple files at the same time, all global variables and functions without the static prefix are globally visible. I will give an example to illustrate this sentence. We need to compile two source files, a. c and main. c at the same time.
The contents of A.C are as follows:
# Include <cstdio> Add this statement
Char a = 'a'; // global variable
Void msg ()
{
Printf ("Hello \ n ");
}
You may ask: why can the global variables a and msg defined in a. c be used in main. c? As mentioned above, all global variables and functions without the static prefix have global visibility, and other source files can also be accessed. In this example, a is a global variable, msg is a function, and there is no static prefix. Therefore, it is visible to other source files main. c.
If static is added, other source files are hidden. For example, if static is added before the definitions of a and msg, main. c will not be able to see them. This feature allows you to define functions with the same name and variables in different files without worrying about name conflicts. Static can be used as the prefix of functions and variables. For a function, the role of static is limited to hiding. For a variable, static has the following two functions.
(2) The second role of static is to keep the variable content persistent. Variables stored in the static data area will be initialized at the beginning of the program, which is also the only initialization. There are two types of variables stored in the static storage area: global variables and static variables, but compared with global variables, static can control the visible range of variables. static is used to hide the variables.
(3) The third role of static is that the default Initialization is 0. In fact, global variables also have this attribute, because global variables are also stored in the static data zone. In the static data area, the default values of all bytes in the memory are 0x00. In some cases, this feature can reduce the workload of programmers.
Finally, we will summarize the three functions of static in one sentence. First, the main function of static is to hide. Secondly, because static variables are stored in the static storage area, they have persistence and default value 0.
The content of main. c is as follows:
In addition to header files, you must declare the function: void msg ();
Int main (void)
{
Extern char a; // extern variable must be declared before use
Printf ("% c", );
(Void) msg ();
Return 0;
}

Static keywords in C Language

The process-oriented static of C ++ is the same as that of C. The static function of C ++ has two usage methods: static in process-oriented programming and static in object-oriented programming. The former applies to common variables and functions, and does not involve classes. The latter mainly describes the role of static in classes.
I. static in process-oriented design
1. Static global variables
Add the keyword static before the global variable, which is defined as a static global variable. Here is an example of a static global variable:
// Example 1
# Include <iostream. h>
Void fn ();
Static int n; // defines the static global variable.
Void main ()
{N = 20;
Cout <n <endl;
Fn ();
}
Void fn ()
{N ++;
Cout <n <endl;
}
Static global variables have the following features:
This variable allocates memory in the global data zone;
Uninitialized static global variables will be automatically initialized to 0 by the program (the values of automatic variables are random unless they are explicitly initialized );
Static global variables are visible in the entire file declared, but invisible outside the file;
All static variables are allocated memory in the global data zone, including the static local variables to be mentioned later. For a complete program, the distribution in the memory is as follows:
Code Area
Global data Zone
Heap Area
Stack Zone
In general, dynamic data generated by new is stored in the heap zone, and automatic variables in the function are stored in the stack zone. Automatic variables usually release space as the function exits, and static data (even static local variables in the function) is stored in the global data zone. The data in the global data zone does not release space because the function exits. Careful readers may find that
Static int n; // defines the static global variable.
Change
Int n; // defines the global variable
The program runs normally.
Indeed, defining global variables can share variables in files, but defining static global variables has the following benefits:
Static global variables cannot be used by other files;
Variables with the same name can be defined in other files without conflict;
You can change the Sample Code as follows:
// Example 2 // File1
# Include <iostream. h>
Void fn ();
Static int n; // defines the static global variable.
Void main ()
{N = 20;
Cout <n <endl;
Fn ();
}
// File2
# Include <iostream. h>
Extern int n;
Void fn ()
{N ++;
Cout <n <endl;
}
Compile and run Example 2, and you will find that the above Code can be compiled separately, but an error occurs during running. Try
Static int n; // defines the static global variable.
Change
Int n; // defines the global variable
Compile and run the program again to understand the differences between global variables and static global variables.
2. Static local variables
Before a local variable, add the keyword static to define the variable as a static local variable.
Here is an example of static local variables:
... The remaining full text>
 

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.