-1

I have this source of a single file that is successfully compiled in C:

#include <stdio.h>

int a;
unsigned char b = 'A';
extern int alpha;

int main() {
    extern unsigned char b;
    double a = 3.4;
    {
        extern a;

        printf("%d %d\n", b, a+1);

   } 
return 0;
} 

After running it, the output is

65 1

Could anybody please tell me why the extern a statement will capture the global value instead of the double local one and why the printf statement print the global value instead of the local one?

Also, I have noticed that if I change the statement on line 3 from

int a;

to

int a2;

I will get an error from the extern a; statement. Why does not a just use the assignment double a=3.4; ? It's not like it is bound to be int.

user2565010
  • 1,876
  • 4
  • 23
  • 37
  • 1
    Check here please: [What does external linkage mean](http://stackoverflow.com/questions/23846057/what-does-external-linkage-mean/23846114#23846114), and of course [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – πάντα ῥεῖ May 27 '14 at 20:38
  • That wouldn't even compile in C++. Maybe you should remove that tag. – juanchopanza May 27 '14 at 20:41

2 Answers2

1

The line

extern a; 

shadows the previous declaration. Until the scope where this is declared ends, this declaration takes precedence over the definition

double a = 3.4;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

It's not like it is bound to be int.

Actually, it is. In the declaration

extern a;

The (implicit) type of a is indeed int. Declarations in C without any specific type always default to int.

In addition, an extern declaration cannot refer to a local variable (even one declared within the same function).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285