C zero-based video -44- static local variables, static global variables, static functions

The static keyword

static keyword in C language, for variety, which can be used to modify the local and global variables and functions, respectively static local variables, static global variable and static functions.

Static local variables

Modified using static local variable, you get a static local variable :

static int nValue = 0;

Static local variable characteristics:

  • Initialized only once
  • You can only be used within the definition of the function
void FunTest()
{
    static int nValue = 0;
    nValue++;
    printf("nValue:%d\r\n", nValue);
}


int main(){
    FunTest();
    FunTest();
    FunTest(); 
    FunTest();
    FunTest();
    return 0;
}

Both static local variable as a global variable that can transmit information in a number of function calls, but also limited access to only one function, to avoid the abuse of the variables global variables caused confusion.

Static global variables

If you are using a modified static global variable, you get a static global variable. In the same file, static global variable and the global variable no difference, can be accessed, modified several functions:

static int nValue = 0;

void FunTest1()
{
    nValue++;
    printf("nValue:%d\r\n", nValue);
}

void FunTest2()
{
    nValue *= 100;
    printf("nValue:%d\r\n", nValue);
}


int main(){
    FunTest1();
    FunTest2();
    return 0;
}

With the exception that the global variable, static global variables can only be a function of the current c file access. Static global variables can be viewed as limiting the scope of global variables.

Static function

Use static modification function, you get static functions, static function can only be called a function of the current c file.

Guess you like

Origin www.cnblogs.com/shellmad/p/11695687.html