简体   繁体   中英

what's the meaning of a static local variable in C?

 BOOL foo(void){

    static BOOL displayed = FALSE;
    static BOOL initialized = FALSE;

    if (displayed)
        return FALSE;

    //more code 

    displayed = TRUE;
    return FALSE;
}

what's the meaning of a static local variable in C ?

if this method is called a second time, the displayed won't be re-initialized to FALSE?

Static local variables are initialized once only, before program startup. Their values then persist between invocations.

From the standard, section 6.2.4/3 Storage durations of objects:

An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

Static variables are initialized only once. This can be used in special cases like counting the no of run-time executions of a function. The static variables have a life time same as global variables. But their scope is limited to where it is defined.

the initialization is performed only once at the time of memory allocation by the compiler. The variable retains its value during program execution.

Static automatic variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function. The scope of static automatic variables is identical to that of automatic variables, ie it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program. Static variables may be initialized in their declarations; however, the initializers must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM