Consider the code:
#include <stdio.h>
int x;
int main (void)
{ }
The value of x
is 0
inside main
. But why is that? I have not declared it to be static
. Or is it assumed static
as it is outside a function?
If the above is true, how does it make it different from an extern
?
It's neither static
nor extern
. It's a variable visible for the compilation unit it's in, and additionally will be visible from all compilation units that declare x
to be an extern
variable.
Why am I saying it's neither static
nor extern
?
If it was extern
, then, there must be a different compilation unit with x
declaration on it. Clearly this is your only compilation unit.
If it was static
then, no extern
reference would be allowed to x
variable defined in this compilation unit. We know that we could easily declare an extern
variable to this x
declared here.
Why is 0
assigned to x
? Because, in C, all global variables initialize to 0
. It says so in 6.7.8 (10) of the C99 standard.
When we say that variables of "static storage duration" are initialized to 0 implicitly, we don't mean that you need to put the "static" keyword in front of them.
"static storage duration" merely is a specific kind of storage duration for objects that says that their storage lasts for the complete duration of the program. This kind of storage duration is used for variables declared at file scope (like your variable) and local static variables.
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