I wrote a piece of code like this
int a;
int a = 100;
int main()
{
}
It was compiled successfully by GCC, but not by G++.
I guess GCC handle this by ignoring the first definition of variable a. But I want to know the precise rule so that I won't miss anything.
Can anyone help me out?
In C
int a; /* Tentative definition */
int a = 100; /* Definition */
From 6.9.2 External object definitions in C11 specs:
A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.
int i4; // tentative definition, external linkage static int i5; // tentative definition, internal linkage
In C++
int a;
is a definition (not tentative) and because it is illegal to have multiple definitions of an object, it will not compile.
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