Tuesday, January 15, 2008

Storage Classes in C++

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!

2 comments:

Anonymous said...

what is your opinion about mutable storage class.
i think if we are talking about c++ we should discuss about mutable
plz don't furnish incomplete information on net

Bhargav-------------------------------------------- said...

Thanks for your comment. But did I ever say my blog is the-go-to resource on the internet?
Anyway if you want to know what mutable storage class is ...

Mutable allows a const member to modify const data.

Google up son!