Introduction to Programming Languages/Static Memory

From Wikibooks, open books for an open world
< Introduction to Programming Languages
Jump to: navigation, search

Static memory[edit]

When a programmer declares a global variable, such as `global_var`, `global_const`, or `global_const2`, they can go into either data or bss section, depending on whether they were initialized or not. If they were, they go into the data section. If not, they go into the bss section. Static variables work the same way as globals: they go either into the data or bss section, depending on their initialization.

Notice that the size of these segments is known at compilation time. The only difference between data and bss is initialization. It is also important to point out that global and static variables zero-initialized by the compiler go into bss. Thus, `static_var_u` goes to bss whereas `static_var` goes to data.


Scope of static variables[edit]

Static variables behave almost global variables: while local variables lose their value every time the function exits, static variables hold their value across function calls. The following program shows this behavior:


#include <stdio.h>
 
int counter1() {
  static store = 0;
  store++;
  printf("Counter 1 = %d\n", store);
  return store;
}
 
int counter2() {
  static store = 0;
  store++;
  printf("Counter 2 = %d\n", store);
  return store;
}
 
int main() {
  int i;
  char* s = "Counter = ";
  for (i = 0; i < 5; i++) {
    if (i % 2) {
      counter1();
    } else {
      counter2();
    }
  }
}


Running the program above, we see that, despite having two variables named `store`, they are different variables. That is enough to show that the scope of static variables is not global, as we might think judging from their behavior.