C/Storage Classes

From Wikiversity
< C
Jump to navigation Jump to search

C Storage Classes[edit]

Storage classes define the longevity and scope of variables and functions. There are two types of storage classes: automatic and static. There are several storage class specifiers:

  • auto: this is the default storage class specifier for variables defined inside a function. auto can be used only inside functions. Variables declared auto will automatically have their storage allocated on entry to a function and deallocated when the function exits. auto variables contain garbage until explicitly initialised. Use of auto is archaic and there is no need to use it.
  • register: this storage class specifier can be used to indicate to the compiler that the variable will be used frequently and it should be placed in a CPU register, if possible. However, defining a variable with this specifier does not guarantee that it will be stored in a CPU register (a compiler can ignore it) and modern compilers should allocate registers much better than a programmer can.
  • static: this storage class specifier is used for two main purposes as given below
    • For local variables: when a local variable is defined with the static storage class specifier, it is initialized to 0 by default in the absence of an explicit initialisation value. A static variable in a function definition will retain its value across multiple calls to the function.
    • For global variables and functions: When a global variable or a function is defined as static, its scope is reduced to the C program file in which it is defined. Thus even though it is a global variable, it can not be accessed from another module (it is said to have internal linkage).
  • extern: this storage class specifier is used to declare a variable or function that is defined in another module. For function declarations, the storage class extern can be omitted.

Storage classes can be remembered easily by remembering RASE, i.e., Register Auto Static Extern.

Project: Topic:C
Previous: Type Qualifiers — C/Storage Classes — Next: Typecasting