In this c program
a=8;
main()
{
printf("%d", a);
}
variable a has been declared without any data type and still this program compiles successfully and gives the desired output.
output ::
8
see it on ideone.
but, when i declared the same variable inside main, it gives compilation error.
main()
{
a=8;
printf("%d", a);
}
output ::
prog.c:2: warning: return type defaults to ‘int’
prog.c: In function ‘main’:
prog.c:3: error: ‘a’ undeclared (first use in this function)
prog.c:3: error: (Each undeclared identifier is reported only once
prog.c:3: error: for each function it appears in.)
prog.c:4: warning: implicit declaration of function ‘printf’
prog.c:4: warning: incompatible implicit declaration of built-in function ‘printf’
see here.
How the first program is working but the second?
What you see here is the “Implicit Int Rule” at work. Simply put the rule says:
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.
EDIT:
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
aand hence reports the error.[Ref 1]
C99 Standard: Foreword
Para 5: