Reputation: 50831
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?
Upvotes: 26
Views: 1486
Reputation: 134356
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 [...]
Upvotes: 40
Reputation: 33
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.
Upvotes: 2