Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring two global variables of same name in C

Tags:

c++

c

scope

global

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;
}
like image 513
ATul Singh Avatar asked Jun 30 '13 08:06

ATul Singh


People also ask

Can 2 global variable have same name?

2 Answers. Show activity on this post. In C, multiple global variables are "merged" into one. So you have indeed just one global variable, declared multiple times.

Can two variables have the same name in C?

Said in simple terms, if multiple variables in a program have the same name, then there are fixed guidelines that the compiler follows as to which variable to pick for the execution.

Can we declare the global variable twice in C?

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

Can we create two variables same name?

It's not possible, an if statement has no special scope, so you can't have two variables with the same name within the same scope and access both, the latter will overwrite the former, so they should have different names.


1 Answers

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.

like image 58
Mats Petersson Avatar answered Sep 30 '22 23:09

Mats Petersson