static variables [closed]
can anyone explain when static variables should be used and why?
There are 2 distinct uses of the static
keyword in C:
- Static declarations in a function's scope
- Static declarations outside of a function's scope
(MOSTLY) EVIL: Static Variables in a function
A static variable in a function is used as a "memory" state.
Basically, your variable is initialized to your default value only the first time you call it, and then retains its previous value in all the future calls.
It is potentially useful if you need to remember such state, but the use of such statics is usually frowned upon because they are pretty much global variables in disguise: they will consume your memory until the termination of your process once.
So, in general, making localized functions is EVIL / BAD.
Example:
#include <stdio.h>
void ping() {
static int counter = 0;
return (++counter);
}
int main(int ac, char **av) {
print("%d\n", ping()); // outputs 1
print("%d\n", ping()); // outputs 2
return (0);
}
Output:
1
2
(MOSTLY) GOOD: Static Variables outside of a function's scope
You can use static outside of a function on a variable or function (which, after all, is sort of a variable as well and points to a memory address).
What it does is limit the use of that variable to the file containing it. You cannot call it from somewhere else. While it still means that that function/var is "global" in the sense that it consumes your memory until your program's termination, at least it has the decency to not pollute your "namespace".
This is interesting because that way you can have small utility functions with identical names in different files of your project.
So, in general, making localized functions is GOOD.
Example:
example.h
#ifndef __EXAMPLE_H__
# define __EXAMPLE_H__
void function_in_other_file(void);
#endif
file1.c
#include <stdio.h>
#include "example.h"
static void test(void);
void test(void) {
printf("file1.c: test()\n");
}
int main(int ac, char **av) {
test(); // calls the test function declared above (prints "file1.c: test()")
function_in_other_file();
return (0);
}
file2.c
#include <stdio.h>
#include "example.h"
static void test(void); // that's a different test!!
void test(void) {
printf("file2.c: test()\n");
}
void function_in_other_file(void) {
test(); // prints file2.c: test()
return (0);
}
Output:
file1.c: test()
file2.c: test()
PS: Don't start throwing stones at me if you're a purist: I know static vars are not evil, they're not exactly globals either, functions are not exactly variables, and there's no actual "namespace" (don't get started on symbols) in C. But that's for the sake of the explanation here.
Resources
- Static Variables
- Is a Static Variable in C Reallocated Every Time I Call a function?
- A Draft of the ANSI C standard (C89)
http://en.wikipedia.org/wiki/Static_variable
In C a variable declared outside of functions as static will not be accessible from outside that file (can't use extern in another file..)
For a local variable in a function, static will make the lifetime of the variable last throughout execution of the program, not just a variable allocated on the stack.
When using static variables, it can really raise issues with multithreading because only one instance of the variable exists - so that needs to be kept in mind.
In C static
means two different things, actually:
1) inside a function it means that the static
variable will remain in existence after the function has exited
2) otherwise it means that the static
variable or function is local to that compilation unit (“file”), i.e. not externally visible
Depends on what scope you are talking about.
Static inside a function, inside a class definition or in front of a global variable?
In a function it is good when you need to prevent a variable from being reinitialized. Below number of times will be 10.
for(int z=0; z<10; z++)
{
static int number_of_times = 0;
number_of_times++;
}
Another use is when we need to preserve information about the last value a function returned.
If you wanted to number instances of a class, you can use a static member variable to keep track of them
Following that, static member functions can be used to modify static member variables to keep track of their values
Global static variables inside a file of code indicates other files that are part of the project cannot access the variable. Only the code in the file can. (simulate object oriented code)
精彩评论