1

I have a few doubts regarding the following statement:

C allows a global variable to be declared again when first declaration doesn’t initialize the variable.

Consider the following snippet:

#include<stdio.h>
int x;                       //line 1
int x = 5;                   //line 2  
int main(void)
{
  printf("%d", x);
  return 0; 
}

OUTPUT: 5

Q1. In line 1, the first declaration of x does initialize the global variable x to 0 by default. Then why does the compiler not throw any error? If I rewrite line 1 and line 2 as:

int x=10;
int x=20;

The above snippet results in an error like redefinition of 'x'. Shouldn't I get the same error for the following also because x is, by default, initialized to 0?

int x;
int x=5;

Q2. Both the line 1 and line 2 are defining the global variable x. Is this statement correct? I have read that we can define a variable only once but we can declare it as many times as we want.

Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43
  • 2
    There is an "explicit" missing in that statement. Do not just post some phrase you caught from somewhere. – too honest for this site Oct 04 '15 at 12:09
  • Related: [Why 'extern' storage class works differently in functions?](http://stackoverflow.com/questions/32535793/why-extern-storage-class-works-differently-in-functions/32536140#32536140) – P.P Oct 04 '15 at 12:18
  • Thanks for your comments. I was not familiar with the concept of tentative definitions. These links were really helpful: http://stackoverflow.com/questions/3095861/about-tentative-definition?lq=1 http://stackoverflow.com/questions/5337370/redefinition-allowed-in-c-but-not-in-c?lq=1 – Gurmanjot Singh Oct 04 '15 at 12:49

0 Answers0