23
votes

I wonder if this yields in undefined behaviour:

printf("Test %d %s", 123, "abc", "def", "ghi");

The first two arguments after the format string match the format string, so these are OK; but the 3rd and 4th arguments are in excess because there are no more corresponding format specifiers.

IMHO printf() should simply ignore these excess arguments and there should be no UB. Is this correct?

2
I think this question is like asking "Can a function that accepts varargs take any number of arguments?". The mechanism that allows the handling of a variable number of arguments works whatever the particulars of how the function uses those arguments... - SJuan76

2 Answers

37
votes

Yes, this scenario is explicitly defined by the standard. It is not undefined behaviour.

To quote the C11 standard, chapter ยง7.21.6.1, The fprintf() function

[...] If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored [...]

2
votes

Basically, printf (or any formatting function) will look into only 'n' number of %d, %c, %f..., etc in the format string from the variable list argument. Others are simply ignored.