Bloomberg LP Interview Question
Financial Software DevelopersCountry: United States
Interview Type: Phone Interview
I would say like this. A variable is "global" when it's declared in the global namespace. Variables in the global namespace persist throughout the lifetime of the global namespace, that is, until the program's termination. "static" makes a variable persistent throughout the program's lifetime, which is pretty much what happens to global variables too, however "static" really is a way of saying "this variable is not automatic", and can be used anywhere. When "static" is applied to a variable in the global namespace, the side effect is that such variable becomes private to the compilation unit where it is declared, and cannot be referenced by other units using the "extern" qualifier. This practice is actually considered obsolete and should be replaced with that of encasing such variables in the unnamed namespace.
There are three cases when the static keyword can be applied, the first two are similar:
1. A variable declared (actually defined) as static outside of any block
In this case this variable has file-scope (can be only be accessed in the file where it is declared and after the declaration) and has storage allocated for the full lifetime of the program
2. A variable declared static in a block
In this case the usual block-scope applies but the life-time of the storage is the full life-time of the program
1&2: If the variables are not initialized their value is set to 0. If there is an initialization it must be constant and it is evaluated at compile time and the initial value is set to this.
3. A function is declared as static - it means that the function (which are by default have external linkage!) has file linkage only, so it cannot be from called outside of the file.
Some examples:
static int my_static; // file-global declaration (case 1)
can be accessed in the file, but declaring it as "extern int my_static;" and trying to use it in another file will result a linker error.
2.
void f() {
static int my_static = 0;
my_static++;
printf("Function is now called %d times\n", my_static);
}
3.
In file x.c:
static void f() {
// do something
}
In file y.c
extern void f();
...
f();
it will compile but when the object files from x.c and y.c are linked together there will be no extern f found.
Both static and global variables have lifetime extending across the entire run of the program. However, local variables can also be static, for instance
- Sharma February 13, 2012void foo() { static int i = 0; } declares a static local variable.
In addition, a static variable only has scope in the file in which it is declared, whereas variables declared without static keyword can be accessed from other files using an extern declaration.