Summary of static usage in C Language

Source: Internet
Author: User

I. cProgramBucket Layout

C Programs are always composed of the following parts:

1)Body section-- Machine commands executed by the CPU; a program has only one copy; read-only, to prevent the program from modifying its own commands due to accidents;

2)Initialize data segments (data segments)-- All the global variables with initial values in the program are stored here.

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 and environment information ).

5) Heap-dynamic storage.

| ----------- |
|
| ----------- |
| Stack |
| ----------- |
|
| \ |/|
|
|
|/| \ |
|
| ----------- |
| Heap |
| ----------- |
| Not initialized |
| ----------- |
| Initialization |
| ----------- |
| Body segment |
| ----------- |

Ii. Static in process-oriented programming

1. Global static variables

When the keyword static is added before the global variable, the global variable is defined as a Global static variable.

1) location in memory:Static storage Zone(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:Global static variables are invisible outside the declared files. Accurately starts from the definition to the end of the file.

Let's take a look at the program about the scope:

 // Teststatic1.c  
Void Display ();
Extern Int N;
Int Main ()
{
N = 20 ;
Printf ( " % D \ n " , N );
Display ();
Return 0 ;
}

// Teststatic2.c
Static Int N; // Defines Global static variables, automatically initialized to 0, only visible in this file
Void Display ()
{
N ++;
Printf ( " % D \ n " , N );
}

The file is compiled separately, but the Variable N in teststatic1.c cannot be found during link, resulting in an error.

Benefits of defining global static variables:

<1> cannot be accessed by other files. Modify

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

2. Local static variables

When the keyword static is added before the local variable, the local variable is defined as a local static variable.

1) location in memory:Static storage Zone

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 scope is still a local scope. When the function or statement block that defines it ends, the scope ends.

Note: When static is used to modify local variables, it changes the storage location of local variables,SlaveThe original stack storage is changed to a static storage zone.. However, after leaving the scope, the local static variables are not destroyed, but still resident in the memory until the program ends, but we cannot access them any more..

When static is used to modify the global variable, it changesScope of global variables(It is invisible outside the file Declaration), but it does not change its storage location, or it is still in the static storage area..

3. 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.

For example:

  //  Teststatic1.c  
Void Display ();
Static Void Staticdis ();
Int Main ()
{
Display ();
Staticdis ();
Renturn 0 ;
}

// Teststatic2.c
Void Display ()
{
Staticdis ();
Printf ( " Display () has been called \ n " );
}

Static Void Staticdis ()
{
Printf ( " Staticdis () has been called \ n " );
}

The file is compiled separately, but the staticdis () function cannot be found during the connection, resulting in an error.

Benefits of defining static functions:

<1> functions with the same name can be defined in other files without conflict.

<2> static functions cannot be used by other files.

The storage specifiers auto, register, extern, and static correspond to two storage periods: 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.

Some specific functions can be implemented due to the above features of static variables.

1. Count statistics function

Declare a local variable of the function and set it to the static type as a counter so that the function can be counted every time it is called. This is the best way to count the number of function calls, because this variable is closely related to the function, and the function may be called in multiple different places, therefore, it is difficult to collect statistics from the caller's perspective.CodeAs follows:

VoidCount ();
IntMain ()
{
IntI;
For(I =1; I <=3; I ++)
Count ();
Return 0;
}

VoidCount ()
{
StaticNum =0;
Num ++;
Printf ("I have been called % d", Num,"Times \ n");
}

Output result:

I have been called 1 times.

I have been called 2 times.

I have been called 3 times.

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.