Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of a variable outside main in C

Tags:

c

variables

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?

like image 770
Kanishk Avatar asked Feb 24 '11 20:02

Kanishk


2 Answers

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.

like image 159
Pablo Santa Cruz Avatar answered Nov 18 '22 13:11

Pablo Santa Cruz


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.

like image 6
Johannes Schaub - litb Avatar answered Nov 18 '22 11:11

Johannes Schaub - litb