C language basics: static keyword

This article combines work experience to study the usage of the static keyword in C language.

1 static keyword concept

The static keyword is very commonly used in C language. There are three common usages in bloggers' work: modifying global variables, modifying local variables, and modifying functions. Through the modification of the static keyword, the modified variable or function can only be valid in the scope, similar to a privatization mechanism.

2 Usage and usage scenarios

2.1 Modifying global variables

2.1.1 Code example

Variables defined outside a function are called global variables. The word "global " means that this variable can also be called in other c files.

For example, the following code demo1.c, main.c:

//demo1.c

int demo_a;

void demo1(void)
{
    
    
	demo_a = 10;
}
//main.c

#include <stdio.h>

extern int demo_a;
extern void demo1(void);

int main()
{
    
    
    demo1();
    printf("demo_a = %d\n", demo_a);
}

First, a global variable demo_a is defined in demo1.c, and a function demo1(void) is used to assign 10 to the global variable.

Then, use the extern keyword in the main function to externally declare the global variable demo_a and the function demo1(void). In the main function, assign demo_a a value of 10 by calling demo1(), and then compile the software and print it out.

The results printed on the console are as follows:

insert image description here
This demo is a piece of cake for those who are familiar with C language. The reason why the value of demo_a can be called in other c files is because the scope of global variables is in the c files of the entire project.

Then on this basis, if the keyword static is added to modify the global variable demo_a, as shown in the figure below:

//demo1.c

static int demo_a;//加上关键字static修饰全局变量demo_a

void demo1(void)
{
    
    
	demo_a = 10;
}

Compile again and an error will be reported:
insert image description here
The error reported here means that during the process of software linking, the variable demo_a cannot be found by searching all the c files in the project. Because the static keyword limits the scope of the variable demo_a to the demo1.c file, other external files cannot be referenced even if extern is declared.

2.1.2 Usage Scenarios

In the blogger's work experience, the use of static to modify the global variable is to limit the use of the global variable in its own c file to prevent other c files from being tampered with at will. For example, in the previous section, external files cannot access the value of demo_a at all.

What if you want to get the value of a static global variable. It can be obtained by calling the function return value and changing the code as shown in the figure below.

//main.c

#include <stdio.h>

extern int demo1(void);

int main()
{
    
    
    int demo_a = demo1();    
    printf("demo_a = %d\n", demo_a);
}

//demo1.c

static int demo_a;

int demo1(void)
{
    
    
	demo_a = 10;
	return demo_a;
}

Return the value of demo_a to the main function through the demo1() function, so that the outside can obtain the value of the static global variable. Note that the demo_a variable appears in both demo1.c and main.c files, but it is not the same thing. One is a static global variable, and the other is a local variable in the function. That is to say, changing the value of the local variable demo_a to other values ​​(such as 20) in the main function will not affect the static global variable demo_a in the demo1.c file. In this way, external files can only be read but not written, achieving the effect of not only transmitting information to the outside world, but also preventing tampering.

2.2 Modifier function

2.2.1 Code example

Change the code in the previous section slightly, as follows:
For example, the following code demo1.c, main.c:

//demo1.c

int demo_a;

static void demo1(void)
{
    
    
	demo_a = 10;
}
//main.c

#include <stdio.h>

extern int demo_a;
extern void demo1(void);

int main()
{
    
    
    demo1();
    printf("demo_a = %d\n", demo_a);
}

Add the static keyword before the definition of the demo1(void) function in demo1.c to become a static function. At this time, if the demo1(void) function is declared externally through extern in the main function, it cannot be called. The running result is as follows: the
insert image description here
error report is similar to the previous section, and the definition of the demo1(void) function cannot be found. The static keyword also limits the scope of this function to this file.

Change the code slightly to the following form of nested calls:

//main.c

#include <stdio.h>

extern int demo_a;
extern void demo(void);

int main()
{
    
    
    demo();
    printf("demo_a = %d\n", demo_a);
}

//demo1.c

int demo_a;

static void demo1(void)
{
    
    
	demo_a = 10;
}

void demo(void)
{
    
    
	demo1();//demo()函数中调用demo1()静态函数
}

In this way, after running it, it can be printed normally.

This shows that the function modified by static can only be called by other functions inside the file, and cannot be called by extern external declaration in other files.

2.2.2 Usage Scenarios

Bloggers encounter static modification functions in their work scenarios. Several functions are divided into a file function, extracted into several sub-functions, and these sub-functions are modified into static functions with static. Doing so prevents external functions from calling subroutines, restricting calls only within that file.

For example the following code:

//demo1.c

static void demo1(void)
{
    
    
	demo_a = 10;
}

static void demo1(void)
{
    
    
	printf("demo_a = %d\n", demo_a);
}

void demo(void)
{
    
    
	demo1();
	demo2();
}

The demo(void) function calls two other static functions of its own c file, and these two static functions respectively implement two functions: assignment and printing. Then other external functions can call the non-static demo(void) function to execute the following two sub-functions.

2.3 Modify local variables

A local variable is defined inside a function, its scope is limited to that function, and it is released after the function finishes running. If you add static modification before the local variable, it will be different.

2.3.1 Code example

Let's start with an example of a simple local variable:

//main.c

#include <stdio.h>

void demo(void)
{
    
    
    int a = 0;
    a++;
    printf("%d ", a);
}

int main()
{
    
    
    for (int i = 0; i < 5; i++)
    {
    
    
        demo();
    }
}

Define a local variable a in the demo() function, initialize it to 0, then increment by 1 and print it out. In the main function, the demo() function is called 5 times through the for loop, and the printing results of the 5 times are as follows:
insert image description here
5 1s are printed here, because every time the demo() function is entered, int a will open up a new stack space for storage This temporary variable is initialized to 0. Then increment by 1 and print, so 1 is output every time.

Next, change the code a little bit, add static modification before the definition of the int a local variable, and change the code as follows:

//main.c

#include <stdio.h>

void demo(void)
{
    
    
    static int a = 0;//加上static修饰
    a++;
    printf("%d ", a);
}

int main()
{
    
    
    for (int i = 0; i < 5; i++)
    {
    
    
        demo();
    }
}

Run the program again, and the print is as follows:
insert image description here
the printed result becomes 12345, that is to say, after calling the demo() function each time, the value of a is kept until the next call, and then printed out by adding 1.

The reason here is that the static keyword turns the local variable a into a static local variable. The characteristic of static local variables is that they will not be released after the function is called, but will be directly assigned a fixed address and initialized to 0 after compilation (this is similar to global variables). When the demo() function runs every time, since a has been pre-defined, the statement static int a = 0; will not be executed.

2.4.2 Usage Scenarios

The static local variable can achieve the effect of retaining the value of the variable without being released, which is very useful in the development of embedded C language. When a function is scheduled periodically, the static modified local variable can retain the value of the previous cycle.

To give an example of a first-order filtering algorithm, the first-order filtering formula is as follows:

Y(n) = α*X(n) + (1−α)*Y(n−1)

The output value of the first-order filter needs to depend on the last input value, so a static local variable can be used to store the output value of this cycle, and it will become the last output value when the function is called next time. Refer to the following code.

#define Alpha 0.8

void first_order_filter(float input,float* output)
{
    
    
    static float output_previous = 0;
    *output = (1 - Alpha) * output_previous + input * Alpha;
    output_previous = *output;
}

3 Summary

The use of the above three static keywords is common in work.

>>Back to personal blog catalog

Guess you like

Origin blog.csdn.net/u013288925/article/details/130691462