Static Variables in C


Static variables are initialized only once. The compiler persists with the variable till the end of the program. Static variables can be defined inside or outside the function. They are local to the block. The default value of static variables is zero. The static variables are alive till the execution of the program.

Here is the syntax of static variables in C language,

static datatype variable_name = value;

Here,

datatype − The datatype of variable like int, char, float etc.

variable_name − This is the name of variable given by user.

value − Any value to initialize the variable. By default, it is zero.

Here is an example of static variable in C language,

Example

 Live Demo

#include <stdio.h>

int main() {
   auto int a = -28;
   static int b = 8;

   printf("The value of auto variable : %d\n", a);
   printf("The value of static variable b : %d\n",b);

   if(a!=0)
   printf("The sum of static variable and auto variable : %d\n",(b+a));

   return 0;
}

Output

Here is the output

The value of auto variable : -28
The value of static variable b : 8
The sum of static variable and auto variable : -20

Updated on: 25-Jun-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements