Default values of static variables in C


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;

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;
   int b;
   printf("Default value of static variable : %d
", a);    printf("Default value of non-static variable : %d
", b);    return 0; }

Output

Default value of static variable : 0
Default value of non-static variable : 0

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

static int a;
int b;
printf("Default value of static variable : %d
", a); printf("Default value of non-static variable : %d
", b);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements