declaring variables without any data type in c

c, variables

Solution

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 ..... .....

Problem

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?

Original source