What you see here is the "Implicit Int Rule" at work. Simply put the rule says:
"A variable declared without an explicit type name is assumed to be of type int
."
Note that this rule was revoked in the c99 Standard[Ref 1].However, depending on your compiler and its settings, the first example might compile with a warning, or will fail to compile(with strict compilation settings)
If you compile your first example with strict settings adhering to c99 Standard the compiler will tell you the root cause.
check here.
cc1: warnings being treated as errors
prog.c:1: error: data definition has no type or storage class
prog.c:1: error: type defaults to ‘int’ in declaration of ‘a’
prog.c:3: error: return type defaults to ‘int’
prog.c: In function ‘main’:
prog.c:4: error: implicit declaration of function ‘printf’
prog.c:4: error: incompatible implicit declaration of built-in function ‘printf’
EDIT:
why does the first example work but second does not?
Note the emphasis on the words "variable declared" in the rule.
In first example, since the statement is at the global scope it is treated as an Implicit declaration, and the Implicit Int Rule gets applied to it.
In Second example, the statement acts as an Assignment and not a Declaration. Since there is no declaration the Implicit int rule does not apply here. In the absence of any type the compiler cannot determine what is the type of a
and hence reports the error.
[Ref 1]
C99 Standard: Foreword
Para 5:
This edition replaces the previous edition, ISO/IEC 9899:1990
, as amended and corrected
by ISO/IEC 9899/COR1:1994
, ISO/IEC 9899/COR2:1995
, and ISO/IEC 9899/AMD1:1995
.
Major changes from the previous edition include:
.....
.....
— remove implicit int
.....
.....
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…