Lifetime of a Variable in C Language



Storage classes define the scope, lifetime, and binding of variables. To fully define a variables., you need to specify both its type and storage class. A variable name identifies a physical location in computer memory where bits are allocated to store the variable's value.

Every object has a storage class that specifies the duration of its storage, which may be static, automatic, or dynamic, along with other features.

Storage class tells us the following factors ?

  • Where is the variable stored: in memory or in the CPU register?
  • What will be the initial value of a variable if it is not initialized?
  • What is the scope of variable and where can it be accessed?
  • What is the lifetime of a variable?

Lifetime

The lifetime of a variable specifies the duration for which the computer allocates memory to it, from allocation to deallocation.

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

  • Automatic: A variable with an automatic lifetime is created every time its declaration is encountered and destroyed when its block is exited.
  • Static: A variable is created when its declaration is executed for the first time and is destroyed when the execution terminates.
  • Dynamic: The memory for variables is allocated and deallocated through memory management functions.

Storage Classes

There are four storage classes in C language ?

Storage Class Storage Area Default Initial Value Lifetime Scope Keyword
Automatic Memory Till control remains in the block Till control remains in the block Local Auto
Register CPU register Garbage value Till control remains in the block Local Register
Static Memory Zero Value in between function calls Local Static
External Memory Garbage value Throughout program execution Global Extern

Example: 1

Here is a C program demonstrating the automatic storage class. This code illustrates variable shadowing, where each block declares a new i variable, hiding the outer one. The output is 3(innermost block), 2(middle block), and 1(outer block).

#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

We will get the generated output as follows ?

3 2 1

Example: 2

Following is the C program for the external storage class. This code illustrates the use of the extern keyword. The global i is 1, but within main, i is 3. The fun function prints the global i, resulting in the input 3 1.

#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
Updated on: 2025-01-07T10:49:53+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements