Explanation of static variables in C language

Source: Internet
Author: User

Static translation comes out of the meaning of "statically" and "still", meaning in C language is in fact similar to its original intention, meaning "static" or "global", used to modify variables and functions. variables that are modified by the static or the scope or storage domain of the function are changed, and the static -Modified variables exhibit static in the initial values . The benefits of the keyword. Do you want to know What happened to the variable or function scope or storage domain after the static modification, and what was the reason for the change? Please continue to look down!

the memory distribution of a C program

Since static is used to modify variables and functions, and variables and functions are necessary to form a C program , the C program's memory distribution diagram is as follows.

  C The program consists of the following 5 parts:

  1 ) Body Segment --cpu part of the machine instruction executed; A program has only one copy; read-only to prevent the program from modifying its own instructions due to accidental accidents ;

  2 ) Initialize the data segment (data segment) -- All global variables assigned the initial value in the program are stored here.

  3 ) Non-initialized data segment ( BSS segment) -- There is no global variable initialized in the program, and the kernel initializes this segment to 0 .

4) Stack - growth direction: top-down growth, automatic variables and the information (return address; Environment information) needed to be saved each time the function is called.

  5 ) Heap -- Dynamic storage area. Is the data type that extends to the high address, which is the bottom-up extension.

C Program Memory distribution map

The above C program distribution diagram clearly tells us that the variables are stored in the stack or the heap or BSS or data segments, why the variable storage domain is different? In fact, the reason is very simple, white is with them defined in the program in different places, there is no static keyword modification related, defined in different places also shows that they have different scopes.

Second, static modification of the variable

1. Global static variables

The global variable is defined as a global static variable by adding the keyword static before the global variable.

  1 in-memory location: static storage (static storage exists during the entire program run)

  2 initialization: Uninitialized global static variables are automatically initialized by the program 0 (the value of an automatic object is arbitrary unless he is displayed initialized)

  3 Scope : A global static variable is not visible outside the declaration of his file. Start with the definition exactly to the end of the file.

Benefits of defining global static variables:

  <1> will not be accessed by other files, modify

  <2> variables of the same name can be used in other files, and no conflicts will occur .

  2. local static variables

The local variable is defined as a local static variable by adding the keyword static before the local variable.

  1 ) in-memory location: Static Storage Area

  2 initialization: Uninitialized local static variables are automatically initialized by the program 0 (the value of an automatic object is arbitrary unless he is displayed initialized)

  3 Scope: The scope is still a local scope, and when the function or statement block defining it ends, the scope ends.

Note: When static is used to modify a local variable, it changes the location where the local variable is stored and changes from the original stack to a static storage area. but the local static variable is not destroyed after it leaves the scope, but still resides in memory until the program is finished, but we can no longer access it.

When static is used to modify a global variable, it changes the scope of the global variable (which is invisible outside of declaring his file), but does not change its location or in the static store.

Iii. functions of Static modifiers

The function is defined as a static function by adding the keyword staticbefore the return type of the function.

The definition and declaration of a function is extern by default , but the static function is only visible in the file that declares him and cannot be used by other files.
 
Benefits of defining static functions:
  <1> functions with the same name can be defined in other files, no conflicts will occur

<2>static functions cannot be used by other files.
Storage DescriptorAuto,Register,extern,Static, corresponding to two storage periods: automatic storage period and static storage period.
   Autoand theRegistercorresponds to the automatic storage period. A variable with an automatic storage period is established when it enters the block that declares the variable, it exists when the block is active, and is revoked when it exits the block.
Key wordsexternand theStaticused to describe variables and functions that have a static storage period. WithStaticthe declared local variable has a static storage duration (Static Storage Duration), or a static range (static Extent). Although his value remains valid between function calls, the visibility of its name is still limited to its local domain. A static local object is first initialized when the program executes to the declaration of the object.

Iv. Summary

(1) First effect: hidden.

When we compile multiple files at the same time, all global variables and functions that do not have a static prefix have global visibility. For the understanding of this sentence, I would say for example. We want to compile two source files at the same time, one is A.C and the other is main.c.

Here's what a.c.

#include增加这条语句

char a = ' a '; Global variable

void msg ()

{

printf ("hello\n");

}

Here's what main.c .

int main (void)

{

extern char A; extern variable must be declared before use

printf ("%c", a);

(void) msg ();

return 0;

}

The running result of the program is: A Hello

You might ask: Why are global variables A and function msg defined in A.C used in MAIN.C? As mentioned earlier, all global variables and functions that do not have a static prefix have global visibility and other source files can be accessed. In this example, a is a global variable, MSG is a function, and neither has a static prefix, so MAIN.C is visible for additional source files.

If static is added, it is hidden from other source files. For example, before the definition of a and MSG, add STATIC,MAIN.C to see them. With this feature, you can define a function with the same name and a variable of the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables, and for functions, static is limited to hiding, and for variables, static has the following two functions.

(2) The second function of static is to keep the contents of a variable persistent. Variables stored in the static data area are initialized at the start of the program and are the only one initialized. A total of two variables are stored in static storage: Global variables and static variables, except that, compared to global variables, static can control the visible range of variables, in the final analysis, static is used to hide them.

(3) The third function of static is initialized to 0 by default. In fact, global variables also have this property, because global variables are also stored in the static data area. In the static data area, all bytes in memory default values are 0x00, sometimes this feature can reduce the workload of the programmer.

Finally, the static three effect of a sentence summary. First, the primary function of static is to hide, and second, because static variables are stored in the static storage area, it has a persistence and default value of 0.

Here's what main.c.

In addition to the header file, you need to declare the function: void msg ();

int main (void)

{

extern char A; extern variable must be declared before use

printf ("%c", a);

(void) msg ();

return 0;

}

Explanation of static variables in C language

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.