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?)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With