What are the default values of static variables in C?

In C, if an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a NULL pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.

For example, following program prints:
Value of g = 0
Value of sg = 0
Value of s = 0

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int g;  //g = 0, global objects have static storage duration
static int gs; //gs = 0, global static objects have static storage duration
int main()
{
  static int s; //s = 0, static objects have static storage duration
  printf("Value of g = %d", g);
  printf("\nValue of gs = %d", gs);
  printf("\nValue of s = %d", s);
  
  getchar();
  return 0;
}

chevron_right


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

References:
The C99 standard

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


17


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.