Understanding Multiple Variable Declarations in a Program and GCC Compiler Behavior

I tried these three versions of a small program, and I had interesting results. Can someone please help me understand the behavior of the compiler 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>. 
+4
source share
1 answer

In the first example, int A; is a preliminary definition: declaring an identifier in a file area without an initializer and without a storage class or static storage class. You can have several, and all of them will refer to the same variable:

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

The declaration of an identifier for an object having a scope without an initializer, and without a storage class specifier or with a static storage class specifier is a preliminary definition. If the translation unit contains one or more preliminary definitions for the identifier, and the translation unit does not contain external definitions for this identifier, then the behavior is performed exactly as if the translation unit contained the declaration of the scope of this identifier, moreover, the composite type as the end of the translation block, and initializer is 0.

In your second example, A does not belong to the file area. This is a local variable, and this is not a preliminary definition, so you can only have one.

In your third example, region A in the file is a variable different from A inside main (), since they have different regions. Just because the second A is static does not change its volume; the identifier remains visible only from inside main (). This is the case of a variable shadow, where a variable in one area has the same identifier as a variable in the surrounding area (in this case, the main () area and the file area.) The fact that A in the file area as an approximate definition does not affect A inside main ().

+8
source

All Articles