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 thi开发者_如何转开发s with static variables.
Thanks a lot...
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 :).
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.
static
variables are automatically initialised to zero (i.e. as though you had assigned zero to them, causing floats and pointers to become 0.0 and NULL, respectively, even if the internal representation of those values is not all bits zero).
Static variables are always implicitly initialized to zero, so there would be no difference in explicitly initializing x to zero.
精彩评论