Storage Classes in C (C Interview Question - 2)

What is Storage Class:

Storage class determines the scope and lifetime of the variable

What is Scope?

Scope or visibility tells you about the part of the program that can access the variable.

What is lifetime?

Each variable in C is assigned some physical location where it can store some value. The lifetime defines how long the value will be present in that particular location. A variable may have local lifetime or global lifetime. A variable that has global lifetime,its value will be persisted throughout the program, whereas a variable with local lifetime,value will persist in the block which it is defined.

There are four storage classes in C

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


1. auto:

  • Default storage class. If we don't specify any storage class  while defining the variable then by default storage class will be taken as auto
  • Scope: Auto can only be used within functions. If you try to specify a global variable with auto storage class then you will get a compile time error
  • Lifetime: Within the function in which it is defined. Created when the function is called and destroyed when the function terminates.
  • Initial Value: Garbage
  • Storage: stack
2. register:

Register is similar to stack , except the values are stored in register instead of storing in stack
    • scope: similar to auto variables there scope is local to the block
    • Lifetime: Storage is allocated when the function is called and destroyed when the function terminates
    • Initial Value: Garbage
    • Storage: Registers
    • Note: You have to use registers only when a variable is repeatedly used for example counters. We cannot apply unary operator (&) to the register, as it does not have memory allocated to it.
3. static:

  • scope: In the function it is defined locally, else within the file if defined global
  • Lifetime: Value of the static variable persists till the end of the program
  • Initial Value; 0
  • Storage: Initialized variables goes into BSS (Block started by symbol),uninitialized variables,i.e., the variables initialized by compiler will be stored in DATA section
  • Note: Static variables are initialized only once.
4. extern:

  • scope: Throughout the program, visible to all the files
  • Lifetime: End of the program
  • Initial Value: Not initialized, it will be pointing to already defined variable.
  • Storage: Initialized variables goes into BSS, uninitialized variables goes into DATA section

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig