chronodekar chronodekar - 3 months ago 7
C Question

static - used only for limiting scope?

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?)

Answer

The static keyword serves two distinct purposes in C, what I call duration (the lifetime of an object) and visibility (where you can use an object from). Keep in mind the C standard actually uses different words for these two concepts but I have found in teaching the language that it's best to use everyday terms to begin with.

When used at file level (outside of any function), it controls visibility. The duration of variables defined at file level are already defined as being the entire duration of the program so you don't need static for that.

static variables at file level are invisible to anything outside the translation unit (the linker can't see it).

When used at function level (inside a function), it controls duration. That's because the visibility is already defined as being local to that function. In that case, the duration of the variable is the entire duration of the program and the value is maintained between invocations of the function.