Static Storage Class in C (Keyword)

Static Storage Class

Static Storage Class in C

  • Static variables can be used within function or file.
  • Unlike global variables, static variables are not variables outside their fucntions or file, but they maintain their values between calls.
  • The static specifier has different effects upon local and global variables.
  • Static Storage Class can be implemented via 2 ways
  • First is Local Implementation of Static Storage Class
  • Second is Global Implementation of Static Storage Class.

Local Implementation of Static Storage Class

  • When a static Specifier is applied to function or block the compiler created permanent storage for it.
  • Static Local variable remains visible only to the function or block in which it is defined.
  • A Static Local variables is a local variable that retains its value between functions calls

Output

0    1

1    2
#include<stdio.h>
void demo()
{
    static int i = 1;
    {
static int i;
printf("%d ",i);
i++;
}
printf("%d\n",i);
i++;
}

int main()
{
demo();
demo();
}

Global Implementation of Static Storage Class

  • When static specifier is applied to a global variable or a function then compiler makes that variable or function known only to the file in which it is defined.
  • A static global variable is a global variable with internal linkage.
  • That means even the variable is global but other files are not having any knowledge of it.
  • Other file cannot access or alter it’s content directly.

Output

a = 1
b = 100

a = 1
b = 101
#include <stdio.h>
void func_1();
int a, b = 10;
int main()
{
    func_1();
    func_1();
    return 0;
}

void func_1()
{
    int a = 1;
    static int b = 100;
   printf("a = %d\n", a);
    printf("b = %d\n\n", b);
    a++;
    b++;
}

2 comments on “Static Storage Class in C (Keyword)”