static - used only for limiting scope?

2019-04-07 11:06发布

Is the static keyword in C used only for limiting the scope of a variable to a single file?

I need to know if I understood this right. Please assume the following 3 files,

file1.c

int a;

file2.c

int b;

file3.c

static int c;

Now, if the 3 files are compiled together, then the variables "a" & "b" should have a global scope and can be accessed from any of the 3 files. But, variable "c" being static, can only be accessed from file3.c, right?

Does static have any other use in C ? (other than to limit the scope of a variable as shown above?)

标签: c static scope
7条回答
放我归山
2楼-- · 2019-04-07 12:02

An example to augment Kinopiko’s answer:

#include <stdio.h>

int foo() {
    static int foo = 0;
    return ++foo;
}

int main() {
    printf("%i\n", foo()); // 1
    printf("%i\n", foo()); // 2
}

This can be used for example to return a safe pointer to a local function variable. Or in Objective-C it’s sometimes used to guard against repeated class initialization:

- (void) initialize
{
    static BOOL initialized = NO;
    if (initialized)
        return;
    // …perform initialization…
    initialized = YES;
}
查看更多
登录 后发表回答