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.
- Default for all the variables
- Object is created and destroyed within the block
- eg: auto float x,y;
- 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)
- Lifetime of variable is entire program execution
- static can be applied to local variables defined in functions or to global variables
- Keeps the value even after the function ends, if its a local variable
- Global Scope - visible to any other file - extern
- File Scope - visible to only that file - static
- Block Scope - visible only within the block.
- 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.
- 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.
- 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.
- 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.
- Global variables in C/C++ default to zero, while local variables are garbage!