2
votes

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?

4

4 Answers

3
votes

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.

7
votes

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.

4
votes

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.

2
votes

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.