I came across the following difference related to function definition/declaration between C and C++.
In C++ if I call a function before declaring and defining it,I get the error message ‘function name is invalid identifier’ which is fine for me as it sounds reasonable.
In C with Visual Studio compiler when I compiled the following program I get the error message:
error C2371: 'fun' : redefinition; different basic types
and in gcc-4.3.4 it executed successfully with just this warning:
warning: conflicting types for ‘fun’
Here goes the program:
#include <stdio.h>
int main(){
fun();
return 0;
}
void fun(){
printf("It is fun");
}
So is it fine in C to just call a function and later bother about defining it?! And why the compilers behave differently?
When you call the function without a prototype in C89 (disclaimer: I don’t know about C99), you are implicitly declaring it as
int fun();
Note that in C, other than in C++, the empty parantheses just mean that you haven’t specified what arguments it takes, not that it takes zero arguments.
When you redeclare the function as returning void, you get the warning, but no error. If you return something non-trivial (structs, floats, …) instead of void or if you try to use the int result of the function, then you might be in deep trouble at runtime.