views:

95

answers:

1

Does the following program invoke Undefined Behaviour in C?

int main()
{
    printf("Printf asking: Where is my declaration ?");
}

In the above program there is an implicit declaration of printf(), so is the above code fully standard compliant or it just has some implementation specific behaviour?

+5  A: 

Yes it does. Not having a declaration in scope is UB.

J.2 Undefined behavior

— For call to a function without a function prototype in scope where the function is defined with a function prototype, either the prototype ends with an ellipsis or the types of the arguments after promotion are not compatible with the types of the parameters (6.5.2.2).

Also, note that falling off main is okay in C99 (i.e. semantically equivalent to a return 0;). For pre-C99 compliant compilers you need a return statement where the return type of the main function is a type compatible with int.

dirkgently
Thanks for J.2 , AC :)
Prasoon Saurav
Note that the only reason that point applies is that `printf`'s parameter list ends with an ellipsis. It wouldn't apply to, say, `puts`, since the parameter type is correct.
Matthew Flaschen
Bear in mind that the ellipsis only affects that implementation of the function. Values are pushed onto the stack the same way - this was regarded as one of the conveniences of C - you could push whatever you wanted on the stack but then you'd be responsible for cleaning it up again. On the other hand Delphi required the called routine to clean up the stack.
PP
@PP: What do you mean by 'values are pushed onto the stack" the same way? There are implementation dependent things like calling convention that decide how arguments are passed to functions.
dirkgently