main()
{
f();
}
int f( int i, float fl)
{
printf(\"function\");
}
Why does the above code runs successfully in \'C\' and prints
Old versions of the C programming language permitted function references without earlier declarations. As a legacy, many current compilers still support the old language or aspects of it. This is why some compilers accept the source code you have shown. Your compiler likely has switches that tell it to use a more recent version of the C programming language or to be more strict about adherence to the standard.
C++ was developed more recently and does not have the legacy of functions without declarations.
The different return types work because the assembly language happens to be implemented the same way. For a function returning void, the called routine simply performs its operations and returns. For a function returning int, the called routine performs its operations, puts its final result in a specific processor register, and returns. In the calling routine, when the return value of a function returning int is not used, the calling routine simply ignores what is in the processor register. Because the register is ignored, there is no difference, to the calling routine, between a function returning void and a function returning int. This will not be the case on all target platforms; there can be differences between functions with different return types, especially when the return types are more complicated objects (such as structs). And, if the calling function did use the return value, the return type would make a difference. The function returning void would leave some uncontrolled value in the processor register where a return value is supposed to be, and the calling function would use that and get unexpected results.
As should be apparent, none of this is behavior you should rely on. It is good practice to use the compiler switches that specify you would like stricter adherence to the standard and would like more warnings. (I would prefer these be the default for compilers.) And it is good practice to write code that conforms to the standard.
The error does not show in C because you're not using the proper flags in the invocation of your compiler.
What is your compiler?
If it's gcc
, try gcc -std=c99 -pedantic -Werror ...
Because C allows the implicit declaration of functions. Or at least it did; C90 may require a declaration, I'm not sure. But since not declaring functions was common practice in C for such a long time, I would expect most compilers to continue to allow it, even after it is banned.
Because C and C++ are different languages. C++ has never allowed implicitly declaring functions.
Because historically, C didn't have a void
type; functions with no
return value were declared int
, even if they didn't return anything,
and there's no problem as long as you don't attempt to use the
(non-existant) return value.