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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With