how is definition of a function after its use in a function call interpreted?
Consider this code:
int main()
{
int e;
prn(e);
return 0;
}
void prn(double x,int t)
{
}
Why does this code gives following warnings and no errors?
m.c:9: warning: conflicting types for ‘prn’
m.c:5: note: previous implicit declaration of ‘prn’ w开发者_运维百科as here
Shouldn't it give a "undefined function" error?
In C99 it should give an undeclared function error.
In C89/90 declaring functions is not mandatory. If an undeclared function is called, the compiler will assume that it returns int
and it will pass arguments to it after subjecting them to so called default argument promotions. In other words, the compiler will try to deduce what that function is from the actual call. If later the function is defined differently from what the compiler deduced, the behavior is undefined. Normally compilers will complain about it with a warning.
This is what you observe in your case. When the compiler sees the prn(e)
call it assumes that prn
is int prn(int)
function. But later it discovers that it is actually a void prn(double, int)
. The mismatch is causing the warning.
In this case you are lucky in a sense that the call to undeclared function takes place in the same translation unit where the function is defined. So the compiler has a chance to compare the call and the definition and issue a warning about the conflict. If prn
was defined in some other translation unit, the compiler would never have a chance to compare the two, so you'd have a full-fledged undefined behavior on your hands.
C89 has implicit function declarations. If you use a function without declaring it, the compiler assumes it is int prn()
. When this turns out to be wrong (because the return types differ), it's letting you know.
Note that the empty argument list in a function declaration means "parameters not specified", not "no parameters". It's then your responsibility to make sure that the input parameters match between the caller and the callee (which they don't, here), and you might get no help at all from the compiler with that.
In C99 this "feature" was removed. I think it was only ever really in C89 for compatibility with ancient C code. There was a time C didn't have function prototypes at all, you always just had to get it right on your own.
精彩评论