Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C static variables and initialization

If I have a global static variable x like in this code

 #include <stdio.h>
 #include <stdio.h>

 static int x;

 int main(void)
 {

 DO SOMETHING WITH x HERE

 x++;

 }

What will be difference if I opted to initialize x to a value first say as in

static int x = 0;  

before entering "main"?

In my first case where I didn't assign a value to x, does the compiler implicitly know that x is to be set to zero as it's a static variable? I heard that we can do this with static variables.

Thanks a lot...

like image 988
yCalleecharan Avatar asked Dec 06 '22 03:12

yCalleecharan


2 Answers

Static variables with explicit initialization are always initialized to zero (or null-pointer, depending on the type). The C standard §6.7.8/10 has description on this. But explicitly setting it to 0 can help others no need to wonder about the same question :).

like image 140
kennytm Avatar answered Dec 25 '22 12:12

kennytm


There is a nice answer here:

Just a short excerpt:

First of all in ISO C (ANSI C), all static and global variables must be initialized before the program starts. If the programmer didn't do this explicitly, then the compiler must set them to zero. If the compiler doesn't do this, it doesn't follow ISO C. Exactly how the variables are initialized is however unspecified by the standard.

like image 28
Smalcat Avatar answered Dec 25 '22 11:12

Smalcat