What are the local static variables in C language?


A local static variable is a variable, whose lifetime doesn’t stop with a function call where it is declared. It extends until the lifetime of a complete program. All function calls share the same copy of local static variables.

These variables are used to count the number of times a function is called. The default value of static variable is 0. Whereas, normal local scope specifies that the variables defined within the block are visible only in that block and are invisible outside the block.

The global variables which are outside the block are visible up to the end of the program.

Example

Following is the C program for local variable −

 Live Demo

#include<stdio.h>
main ( ){
   int a=40 ,b=30,sum; //local variables life is within the block
   printf ("sum=%d" ,a+b);
}

Output

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

sum=70

Example

Following is the C program for global variable −

 Live Demo

int c= 30; /* global area */
main ( ){
   int a = 10; //local area
   printf ("a=%d, c=%d", a,c);
   fun ( );
}
fun ( ){
   printf ("c=%d",c);
}

Output

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

a =10, c = 30

Example

Following is the C program for the local static variable −

#include <stdio.h>
void fun(){
   static int x; //default value of static variable is 0
   printf("%d ", a);
   a = a + 1;
}
int main(){
   fun(); //local static variable whose lifetime doesn’t stop with a function
   call, where it is declared.
   fun();
   return 0;
}

Output

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

0 1

Updated on: 26-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements