简体   繁体   English

C中的静态局部变量是什么意思?

[英]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 ? C中的静态局部变量是什么意思?

if this method is called a second time, the displayed won't be re-initialized to FALSE? 如果第二次调用此方法, displayed将不会重新初始化为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: 根据标准,第6.2.4 / 3节“对象的存储期限”:

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. 声明了其标识符而没有存储类说明符_Thread_local且具有外部或内部链接或具有存储类说明符静态的对象的对象具有静态存储持续时间。 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. 但是,初始化程序必须是常量表达式,并且当为静态变量分配内存时,初始化仅在编译时进行一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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