ATul Singh
ATul Singh

Reputation: 522

Declaring two global variables of same name in C

I have declared two global variables of same name in C. It should give error as we cannot declare same name variables in same storage class.

I have checked it in C++ — it gives a compile time error, but not in C. Why?

Following is the code:

int a;
int a = 25;
int main()
{

   return 0;
}

Check it out at : Code Written at Ideone

I think this probably is the reason

Declaration and Definition in C

But this is not the case in C++. I think in C++, whether the variable is declared at global scope or auto scope the declaration and definition is happening at the same time.

Could anyone throw some more light on it.

Now when I define the variable two times giving it value two times it gives me error (instead of one declaration and one definition).

Code at : Two definitions now

int a;
int a;
int a;
int a = 25;

int main()
{
return 0;
}

Upvotes: 14

Views: 8929

Answers (2)

Abhishek Ghosh
Abhishek Ghosh

Reputation: 665

This is what the classic text "The C Programming Language" by Dennis Ritchie and Brain Kernighan says:

  1. An external declaration for an object is a definition if it has an initializer.

  2. An external object declaration that does not have an initializer, and does not contain the extern specifier, is a tentative definition.

  3. If a definition for an object appears in a translation unit, any tentative definitions are treated merely as redundant declarations.

  4. If no definition for the object appears in the translation unit, all its tentative definitions become a single definition with initializer 0.

So for example:


extern int a =123; // this declaration is a definition as a is initialized to 123

int a; //this is a tentative definition

int a;
int a;
int a;
/*all the above the three tentative declarations are redundant*/

int a;
int a;
int a;

Futher in the code if no where do something as a=100 where we consider a corresponding to this global scope variable and not any other local variable with the same name and type, then ultimately, the global variable a shall be initialized to 0


Upvotes: 2

Mats Petersson
Mats Petersson

Reputation: 129314

In C, multiple global variables are "merged" into one. So you have indeed just one global variable, declared multiple times. This goes back to a time when extern wasn't needed (or possibly didn't exist - not quite sure) in C.

In other words, this is valid in C for historical reasons so that we can still compile code written before there was a ANSI standard for C.

Although, to allow the code to be used in C++, I would suggest avoiding it.

Upvotes: 15

Related Questions