【C 精进】 Static usage

static modified local variables

This is the most commonly used scenario in current work, used to record the number of times a function or a branch enters. The local variable modified by static inside the function will not be re-initialized in the next call, but retain the last value, so that you can use the variable to achieve some logical control, such as whether it is the first time to enter. At the same time, the variable is only visible by the function, other functions cannot be referenced, but it is saved in the global data area.

void test(int a)
{
    static int count = 0;
    if(a > 1)
    {
        count++;    
    }
    else
    {
        count = 0;
    }
    if(count >= 3)
    {
        //to do something
    }
}

static modifier function

For a project where multiple people cooperate to complete different functional modules, there may be a problem of naming conflicts. If a function called read is defined in both source files, but the implementation is different, then the program link will be wrong. If a function is only used inside a certain source file and does not need to be visible to other files, it can be declared as static.

static void read()
{
    //to do something
}

void main()
{
    read();
}

 

static modification of global variables

Like the modified function, the visible range of the variable is controlled by the source file, and all functions of the source file can share the variable. Variables with the same name can also be declared in other source files.

Published 173 original articles · Like 94 · Visit 210,000+

Guess you like

Origin blog.csdn.net/HEYIAMCOMING/article/details/105565619