Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static - used only for limiting scope?

Tags:

c

scope

static

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

like image 697
chronodekar Avatar asked Nov 25 '09 08:11

chronodekar


People also ask

What is the scope of static?

The scope of the static local variable will be the same as the automatic local variables, but its memory will be available throughout the program execution. When the function modifies the value of the static local variable during one function call, then it will remain the same even during the next function call.

Do static variables go out of scope?

Static variables offer some of the benefit of global variables (they don't get destroyed until the end of the program) while limiting their visibility to block scope. This makes them safer for use even if you change their values regularly.

What is the scope of a static global variable?

A global static variable is one that can only be accessed in the file where it is created. This variable is said to have file scope. In C, the preprocessor directive #define was used to create a variable with a constant value.


1 Answers

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've 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.

like image 186
paxdiablo Avatar answered Sep 23 '22 06:09

paxdiablo