Initialization of static variables in C

CProgrammingServer Side Programming

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.

Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable 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 variables in C language,

Example

 Live Demo

#include <stdio.h>
int main() {
   static int a = 8;
   int b = 10;
   printf("Value of static variable : %d\n", a);
   printf("Value of non-static variable : %d\n", b);
   return 0;
}

Output

Value of static variable : 8
Value of non-static variable : 10

In the above program, two variables are declared, one is static and another is non-static. The variables are initialized with values and displayed as follows −

static int a = 8;
int b = 10;
printf("Value of static variable : %d\n", a);
printf("Value of non-static variable : %d\n", b);
raja
Published on 06-Nov-2018 11:00:54
Advertisements