Explain Lifetime of a variable in C language.

CServer Side ProgrammingProgramming

Storage classes specify the scope, lifetime and binding of variables.

To fully define a variable, one needs to mention not only its ‘type’ but also its storage class.

A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable.

Storage class tells us the following factors

  • Where the variable is stored (in memory or cpu register)?
  • What will be the initial value of variable, if nothing is initialized?
  • What is the scope of variable (where it can be accessed)?
  • What is the life of a variable?

Lifetime

The lifetime of a variable defines the duration for which the computer allocates memory for it (the duration between allocation and deallocation of memory).

In C language, a variable can have automatic, static or dynamic lifetime.

  • Automatic − A variable with automatic lifetime are created. Every time, their declaration is encountered and destroyed. Also, their blocks are exited.
  • Static − A variable is created when the declaration is executed for the first time. It is destroyed when the execution stops/terminates.
  • Dynamic − The variables memory is allocated and deallocated through memory management functions.

Storage Classes

There are four storage classes in C language −

Storage ClassStorage AreaDefault initial valueLifetimeScopeKeyword
AutomaticMemoryTill control remains in blockTill control remains in blockLocalAuto
RegisterCPU registerGarbage valueTill control remains in blockLocalRegister
StaticMemoryZeroValue in between function callsLocalStatic
ExternalMemoryGarbage valueThroughout program executionGlobalExtern

Example

Following is the C program for automatic storage class −

 Live Demo

#include<stdio.h>
main ( ){
   auto int i=1;{
      auto int i=2;{
         auto int i=3;
         printf ("%d",i)
      }
      printf("%d", i);
   }
   printf("%d", i);
}

Output

When the above program is executed, it produces the following output −

3 2 1

Example

Following is the C program for external storage class −

 Live Demo

#include<stdio.h>
extern int i =1; /* this ‘i’ is available throughout program */
main ( ){
   int i = 3; /* this ‘i' available only in main */
   printf ("%d", i);
   fun ( );
}
fun ( ) {
   printf ("%d", i);
}

Output

When the above program is executed, it produces the following output −

3 1
raja
Published on 25-Mar-2021 12:41:13
Advertisements