C Storage Classes

Storage classes in C determine a variable’s scope, visibility, lifetime, and storage location. They include auto, extern, static, and register. The default initial value varies based on the storage class. Scope defines variable visibility, while lifetime dictates its persistence in memory.

Read more: C Storage Classes
  • Scope: The extent to which different parts of a program have access to the variable, determining its visibility.
  • Lifetime refers to the duration for which the variable persists in memory, encompassing the allocation and deallocation of its storage. The scope also influences a variable’s lifetime.
  • variable types(Global variable)
Variable TypeLifetimeScope
Global VariableOnly destroyed when the program terminatesOnly the program
Local VariableAllocated memory when entering the function, destroyed when leavingLimited to the function
  • syntax: storage_class_specifier data_type variable_name;
SpecifiersLifetimeScopeDefault Initialize
autoBlock (inside function)BlockUninitialized
registerBlock (stack or CPU register)BlockUninitialized
staticProgramBlock or compilation unitZero
externProgramBlock or compilation unitZero
(none)Dynamic (heap)nilUninitialized

Auto Keyword

A variable declared inside a function without any specified storage class is termed an auto variable.

  • Only usable within functions.
  • Created and destroyed automatically upon function call and exit, respectively.
  • Compiler assigns them garbage values by default.
  • The stack memory stores local variables.
  • By default, every local variable in a function is of auto storage class.

Example:

void f() {
    int i;    // auto variable
    auto int j;   // auto variable
}

Global variable

  • A variable declared outside any function is a global variable.
  • Any function in the program can change its value.
  • initializing
    • int – 0
    • char – \0
    • float – 0
    • double -0
    • pointer – null

Register Keyword

The register keyword indicates that local variables should be stored in a CPU register for faster access, which is especially useful for counter variables.

Faster than normal variables, but few fit in registers.

While the compiler sees “register” as a suggestion, it ultimately decides. Typically, compilers optimize and determine variable allocation.

Register Note 1:

Attempting to access the address of a register variable results in a compile error. For instance:

int main() {
    register int i = 10;
    int *a = &i; // Compile error
    printf("%d", *a);
    getchar();
    return 0;
}

Register Note 2:

You can use the register keyword with pointer variables. Below is a valid example:

int main() {
    int i = 10;
    register int *a = &i;
    printf("%d", *a); // Output: 10
    getchar();
    return 0;
}

Resistor Note 3:

Register is a storage class, and C prohibits multiple storage class specifiers for a variable. Therefore, you cannot use register with static.

int main() {
    int i = 10;
    register static int *a = &i; // Error
    printf("%d", *a);
    getchar();
    return 0;
}

Register Note 4:

There’s no limit to the number of register variables in a C program. However, the compiler may choose to allocate some variables to registers and others not.


static keyword

  • static means its take only single or same memory.
  • static is initialized only once and remains into existence till the end of program
  • static assigned 0 (zero) as default value by the compiler.
  • A static local variables retains its value between the function call and the default value is 0.
  • If a global variable is static then its visibility is limited to the same source code.
  • Static variables stored in Heap(Not in Stack memory)
  • The following function will print 1 2 3 if called thrice.
  • Example
    • void f() { static int i; ++i; printf(“%d “,i); }
  • In “static int a[20];”, variable “a” is declared as an integer type and static. When a variable is declared as static, it is automatically initialized to the value ‘0’ (zero).

What is a static function?

  • A static function can only be called within the same file, limiting its visibility to that source code.
  • static has different meanings in in different contexts.
  • When specified on a function declaration, it makes the function local to the file.
  • When specified with a variable inside a function, it allows the vairable to retain its value between calls to the function

Extern

  • The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else.
  • The extern declaration does not allocate storage for variables.
  • Used to resolve the scope of global symbol
  • Eg : Example Using extern in same file
main()
{
    extern int x;  //Tells compiler that it is defined somewhere else
    printf("%d",x);   
}
int x=10;    //Global variable x

Variable Initializer

Extern as global variable initializer

  • The extern keyword variable can be initialize when its global

External variable always initialize (Zero) ‘0’

#include "stdio.h"
extern int a;
main(){
    printf("a=%d",a);
    return 0;
}
int a;

/* Output : a=0 */

variable initialize in  global variable

#include "stdio.h"
extern int a;
main(){
    printf("a=%d",a);
    return 0;
}
int a =5;

/* Output : a=5 */

Example

#include <stdio.h> 
extern int a;
int main()
{
    void fun();
    printf("\n a=%d",a);
    fun();
    return 0;
}
int a=7;
    
void fun()
{
    printf("\n in fun a=%d",a);
}

/* Output : 
 a=7
 in fun a=7
*/

variable initialize in  global variable

#include <stdio.h> 
extern int a=5;
int main()
{   
    printf("%d",a);
    return 0;
}

/* Output : 5*/
/* Explanation pritf function print a value as 5. */

variable initialize in  global variable

#include <stdio.h> 
extern int a=5;
int main()
{
    void fun();
    printf("\n a=%d",a);
    fun();
    return 0;
}
int a;
    
void fun()
{
    printf("\n in fun a=%d",a);
}

/* Output : 
 a=5
 in fun a=5
*/

Error while running Linker

#include <stdio.h> 
extern int a;
int main()
{
    printf("\na=%d",a);
    return 0;
}

/* Output : // Error */

/*
  Error[e46]: Undefined external "a" referred in main 
  Error while running Linker 
*/

Extern as local variable initializer

  • The extern keyword variable can not be initialize when its local or inside the function. (an initializer is not allowed on a local declaration of an extern variable)

EXample : an initializer is not allowed on a local declaration of an extern variable

#include <stdio.h> 
int main()
{
  extern int a=5;
  printf("%d",a);
  return 0;
}

/* Output */
// Error[Pe2442]: an initializer is not allowed on a local declaration of an extern variable main.c 

storage class specifier

  • typedef – typedef is the storage class specifier.
    • It does not reserve the storage.
    • It is used to alias the existing type. Also used to simplify the complex declaration of the type.
  • reference links

volatile

  • The compiler omits optimization for objects declared as volatile because code outside the current scope can change their values at any time.

Advantages and Disadvantages

Storage ClassAdvantageDisadvantage
autoAutomatically allocated and deallocated within functionsGarbage values if not explicitly initialized
registerFaster access due to storage in CPU registersLimited availability of register space; Compiler-dependent
staticPersistent value across function callsGlobal scope may lead to namespace pollution; May increase memory usage
externAllows sharing of variables across multiple filesGlobal scope may lead to namespace pollution

Interview Questions

What are storage classes in ‘C’ language?

  • automatic class
  • static class

How many storage class specifiers in “C” language?

  • auto,
  • register,
  • static
  • extern

How many variables scopes are there in “C” language?

  • Body.
  • Function.
  • Program.
  • File.

Previous & Next

Please turn AdBlock off, and continue learning

Notice for AdBlock users

Please turn AdBlock off
Index

Discover more from ArunEworld

Subscribe now to keep reading and get access to the full archive.

Continue reading