Detailed static variable static of C language

In C language, static is used to modify variables and functions. This article introduces the main functions of static in detail. There are detailed code examples in the article. Friends who need it can refer to it.

In C language:

static is used to modify variables and functions

The main functions of static are:

1. Modified local variables - static local variables

2. Modify global variables - static global variables

3. Modified function - static function

 Before explaining static variables, we should understand the difference between static variables and other variables :

 

 

call static variable static

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

//代码2

#include <stdio.h>

void test()

{

    //static修饰局部变量

    static int i = 0;

    i++;

    printf("%d ", i);

}

int main()

{

 int i = 0;

    for(i=0; i<10; i++)

   {

        test();

   }

    return 0;

}

operation result:

Compare the effect of code 1 and code 2 to understand the significance of static modification of local variables.

in conclusion:

Static modification of local variables  changes the life cycle of variables  , so that static local variables still exist outside the scope, and the life cycle ends when the program ends.

 Decorate global variables 

1

2

//add.c

int g_val = 2018;

1

2

3

4

5

6

7

8

9

//代码2

//add.c

extern int g_val;

//test.c

int main()

{

    printf("%d\n", g_val);

    return 0;

}

Code execution:

 

When adding a static static variable to int g_val for modification, an error occurs

Code execution:

 

 

in conclusion:

Global variables themselves have external linkage attributes

The variables defined in the A file can be used in the B file through [Link]

But if the global variable is modified by static, the external link attribute becomes an internal link attribute, and this global variable can only be used in its own source file

static can turn external link attributes into internal link attributes, making the scope of global variables smaller

 modifier function

 

 

in conclusion:

The function itself has the attribute of external linkage

After being modified by static, the external link attribute becomes the internal link attribute

This function can only be used inside the source file where it is located, and other source files cannot be linked and used

This is the end of this article about the detailed explanation of static variables in C language. For more detailed explanations of C language staiic, please search for previous articles or continue to browse

 

Guess you like

Origin blog.csdn.net/q2243088760/article/details/130330290