Tech

Storage Classes–Functions–STRUCTURED PROGRAMMING Course Notes

Storage Classes

A storage class defines the scope (visibility) and life-time (existence) of variables and/or functions within a C++ program.

C++ provides five storage-class specifiers:

  1. auto
  2. register
  3. extern
  4. mutable
  5. static

An identifier’s storage class determines the period during which that identifier exists in memory.

An identifier’s scope is where the identifier can be referenced in a program.

And identifier’s linkage determines whether an identifier is known only in the source file where it’s declared, or across multiple files that are compiled then linked together.

Note: Identifiers in C++ are the names assigned to variables and functions. The valid identifiers are declared using the alphabets from A to Z, a to z, and 0 to 9, (although they can’t begin with a number), or it can include underscore (_). Cannot include special symbols or white spaces.)

  • Keywords ‘auto‘ & ‘register‘ declare variables of the automatic storage class. Such variables are created when program execution enters the block in which they’re defined, they exist while the block is active & they’re destroyed when the program exits the block.
  • Only local variables of a function can be of automatic storage class.
  • The storage-class specifier ‘auto‘ explicitly declares variables of automatic storage class. Local variables are of automatic storage class by default, so keyword ‘auto‘ is rarely used.
  • Keywords ‘extern‘ & ‘static‘ declare identifiers for variables of the ‘static‘ storage class & for functions. Static‘ storage-class variables exist from the point at which the program begins execution & last for the duration of the program.
  • A ‘static‘ storage-class variable’s storage is allocated when the program begins execution. Such a variable is initialized once when its declaration is encountered. For functions, the name of the function exists when the program begins execution as for all other functions.
  • External identifiers (such as global variables & global function names) and local variables declared with the storage class-specifier ‘static’ have static storage class.
  • Global variables are created by placing variable declarations outside any class or function definition. Global variables retain their values throughout the program’s execution. Global variables & functions can be referenced by any function that follows their declarations or definitions.