C language: the role of static keyword

static usage:

In C, the main static definitions 全局静态变量, 定义局部静态变量, 定义静态函数.

1. Define global static variables

Add the keyword static in front of the global variable, and the global variable becomes a global static variable. Global static variables have the following characteristics.

  • a. Allocate memory in the global area.
  • b. If it is not initialized, its default value is 0.
  • c. The variable is visible in this file from the beginning of the definition to the end of the file.

2. Define local static variables

Add the keyword static in front of the local variable, its characteristics are as follows:

  • a. The variable allocates memory in the global data area.
  • b. It always resides in the global data area until the end of the program.
  • c. Its scope is a local scope. When the function or statement block that defines it ends, its scope ends.
#include <stdio.h>

void fn(void)
{
    
    
    int n = 10;

    printf("n=%d\n", n);
    n++;
    printf("n++=%d\n", n);
}

void fn_static(void)
{
    
    
    static int n = 10;

    printf("static n=%d\n", n);
    n++;
    printf("n++=%d\n", n);
}

int main(void)
{
    
    
    fn();
    printf("--------------------\n");
    fn_static();
    printf("--------------------\n");
    fn();
    printf("--------------------\n");
    fn_static();

    return 0;
}
-> % ./a.out 
n=10
n++=11
--------------------
static n=10
n++=11
--------------------
n=10
n++=11
--------------------
static n=11
n++=12

3. Define static functions

Add the static keyword before the function return type, and the function is defined as a static function. Its characteristics are as follows:

  • a. Static functions can only be used in this source file
  • b. The inline function declared in the file scope defaults to the static type
/* file1.c */
#include <stdio.h>

static void fun(void)
{
    
    
    printf("hello from fun.\n");
}

int main(void)
{
    
    
    fun();
    fun1();

    return 0;
}

/* file2.c */
#include <stdio.h>

static void fun1(void)
{
    
    
    printf("hello from static fun1.\n");
}
/tmp/cc2VMzGR.o:在函数‘main’中:
static_fun.c:(.text+0x20):对‘fun1’未定义的引用
collect2: error: ld returned 1 exit status

总结: The difference between global and local static variables defined by static is that the scope and visible domain of global static variables start from the definition of the file to the end of the entire file; while the visible domain of local static variables starts from the definition of the file to the whole At the end of the file, the scope is from the definition of the statement block to the end of the statement block.

Guess you like

Origin blog.csdn.net/houxiaoni01/article/details/105163418