Storage Classes in C++

15 Jan 2008

Courtesy: Dave, UGA

Storage Classes

Storage class specifies where the object exists in memory. Also the lifetime of the variable's storage determines the storage class of the variable/object.

Automatic Storage
  1. Default for all the variables
  2. Object is created and destroyed within the block
  3. eg: auto float x,y;
  4. register storage classes is same as auto storage class. Just that it tells the compiler to place the variable to be put in registers(for better performance)
Static Storage
  1. Lifetime of variable is entire program execution
  2. static can be applied to local variables defined in functions or to global variables
  3. Keeps the value even after the function ends, if its a local variable
Scopes
  1. Global Scope - visible to any other file - extern
  2. File Scope - visible to only that file - static
  3. Block Scope - visible only within the block.
Some funda
  1. extern int globalVariable; This is a variable declaration and this can be specified any number of times. No memory is allocated to this variable yet and thus multiple declarations are allowed. If you have an extern variable and try to access it you get a linker error. To prevent this, you should define a variable of the same name. Then you have actually defined a reference.
    Ex: extern int gv; int gv; //then you can access gv.
  2. int anotherVar; This is a variable definition and this can be done only once. This variable has been allocated memory and falls under the auto storage class.
  3. static int getVar() If this function is present in File1.cc and if you try to invoke getVar() in File2.cc, then this is a compiler error since the scope of this function is limited to the File1.cc only.
  4. static has another purpose in C/C++. You have a static variable in a function foo(), then within foo(), increment the variable and print out the variable. Now within main call foo() three times. Then each time you get a different(incremented) value. That is the lifetime of the variable is "complete" program. As long as the program runs, the variable value would be stored. The value is restored even after the function returns.
  5. Global variables in C/C++ default to zero, while local variables are garbage!