user366312
user366312

Reputation: 17016

Why am I able to compile and run C programs without including header files?

I have tested this fact on Turbo C++ 3.0, VC++ 2008 express and Borland C++ 6.

If I add a C program with *.C extension to the project, I am able to compile and run the program without including header files. But in this case, some functions (like sqrt(), etc..) are returning erroneous values.

If I add a C program with *.CPP extension to the project, I am not able to compile and run the program without including header files.

Why?

Upvotes: 3

Views: 2844

Answers (4)

stijn
stijn

Reputation: 35921

In C, when the compiler does not find the definition of a function, it assumes it's an external function returning an integer. So the code compiles, and if the linker then finds a function with corresponding name it will run as well. But possibly with unexpected results.

Upvotes: 7

idz
idz

Reputation: 12988

The C++ standard requires a function prototype to be seen before a function is used.

C does not have this requirement. If a C compiler sees an undeclared function it creates an implicit declaration assuming that the function returns int. If the function doesn't really return int unpredictable things will happen, as you are seeing with sqrt.

Upvotes: 2

S.J.
S.J.

Reputation: 1233

By default in C function return type is int, and even if prototype not declared you'll be able to use, for example, libc functions. Of course, if its return value not int, you've got erroneous values.
C++ are more stricter and disallow this.
Also, gcc implements some functions as built-ins. You can try compiling with -fno-builtin options, if you use it.

Upvotes: 4

user2100815
user2100815

Reputation:

If you don't provide a declaration for a function, C makes a guess at it. This guess is almost always wrong, hence your "erroneous values". C++ doesn't do this.

Upvotes: 3

Related Questions