Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding multiple declaration of a variable in a program and GCC compiler behavior

I tried these three versions of a small program and I got some interesting results. Can anyone please help me understand compiler behaviour in each case.

version 1.0

int A;
int A; 
int A;

int main ()
{
   return 0;
}

Result: Got compiled with one copy of A in BSS.


Version 2.0

int main ()
{
   int A;
   int A;
   int A;

   return 0;
}

Result: Failed to compile with complaining for re-declaration.


Version 3.0

int A;

int  main()
{
   static int A;
   return0;
}

result: Compiled with two copy of A in BSS. one is A and another a.<some numeric tag>. 
like image 394
Satpal Parmar Avatar asked Feb 18 '23 20:02

Satpal Parmar


1 Answers

In your first example, int A; is a tentative definition: a declaration of an identifier at file scope without an initializer and either without a storage class or a static storage class. You can have multiple ones, and they will all refer to the same variable:

The standard says: (ISO/IEC 9899:1999 6.9.2)

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with a 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 definitions 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.

In your second example, A is not of file scope. It's a local variable and it's not a tentative definition, so you can only have one.

In your third example, the A at file scope is a different variable than the A inside main(), as they have different scopes. Just because the second A is static doesn't change its scope; the identifier is still only visible from inside main(). This is a case of variable shadowing, where a variable in one scope has the same identifier as a variable in an enclosing scope (in this case the main() scope vs the file scope.) The fact the the A at file scope happens to be a tentative definition does not affect the A inside main().

like image 64
Nikos C. Avatar answered Apr 08 '23 00:04

Nikos C.