What is static storage duration in C?

I have already written a blog post on C storage class specifiers. In this blog post, we only focus on static storage duration. It means in this blog post you will learn what is the meaning of static storage duration in C programming.

The storage duration of a variable determines its lifetime. “Lifetime” is the time period during the execution of a program in which an identifier exists. There are four storage durations in C:

  • Static.
  • Automatic.
  • Dynamic.
  • Thread.

For now, we only focus on the first one. So let’s begin.

Static storage duration in C?

Static storage duration means identifiers have storage and a defined value for the entire duration of the program. The storage for the variable is allocated when the program begins and deallocated when the program ends.

An identifier declared without the storage-class-specifier _Thread_local, either with storage-class-specifier static or with an external or internal linkage has static storage duration.

For example,

#include <stdio.h>

//static duration
int data = 10;

//static duration
static int data2 = 5;

int main()
{
    //static duration
    static int data1 = 20;


    return 0;
}

 

An identifier with static duration is initialized only once, prior to program startup. And its lifetime is the entire execution of the program.

The following example code explains how the variable “value” is initiated only once and retains its value from one entry of the block to the next.

#include<stdio.h>

void updateAndDPrint()
{
    // Initialising a static variable
    static int data = 1;

    // incrementing in the number
    data = data + 2;

    //printing the static variable
    printf("data: %d \n", data);
}

int  main()
{
    //Calling function first time
    updateAndDPrint();

    //Calling function second time
    updateAndDPrint();

    return 0;
}

Output:

data: 3
data: 5

 

Now I believe you have an understanding of static duration but before closing this post I want to remind you of the important point that is scope and storage duration both are different concepts. For example, an identifier with a global lifetime exists throughout the execution of the source program, it may not be visible in all parts of the program.

Let’s understand it with an example code,

#include<stdio.h>

void fun()
{
    // static variable
    static int count = 0;

    /*
      Some piece of code
    */
}

int  main()
{
    printf("%d\n", count);

    return 0;
}

Output:

error: ‘count’ undeclared (first use in this function).

Explanation:

In the above code, the ‘count’ variable is alive throughout the program but its scope is only within the fun(). It is the reason when I try to access the ‘count’ in the main function I am getting errors.

 

Recommended Articles for you: