How to use static to define global static variables in the C language?

In C language, using the keyword static can define a variable as a global static variable. Global static variables have the following characteristics:

  1. The scope of a global static variable is limited to the file in which it is defined, making it visible only within that source file and inaccessible to other source files.
  2. The lifespan of a global static variable lasts from the beginning to the end of a program, aligning with the entire execution process of the program.
  3. The default initial value of global static variables is 0, and if not explicitly initialized, they will be automatically initialized to 0.

Below is an example code demonstrating how to use static to define global static variables.

#include <stdio.h>

static int globalStaticVar;  // 定义全局静态变量

void function1() {
    globalStaticVar = 10;  // 在函数中访问和修改全局静态变量
}

void function2() {
    printf("globalStaticVar: %d\n", globalStaticVar);  // 在函数中访问全局静态变量
}

int main() {
    function1();
    function2();
    return 0;
}

In the example above, globalStaticVar is a global static variable. We assign a value of 10 to globalStaticVar in the function1() function. Then, in the function2() function, we print the value of globalStaticVar. Since globalStaticVar is a global static variable, function2() can access the value modified in function1(). When running the code, the output result is globalStaticVar: 10.

Leave a Reply 0

Your email address will not be published. Required fields are marked *