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?
The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).
So, printf is producing undefined behavior because you are passing it an incompatible type of argument.
Printf can take as many arguments as you want. In the man page you can see a ... at the end, which stands for a var args. If you got 96 times %s in your first argument, you'll have 97 arguments (The first string + the 96 replaced strings ;) )
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 [...]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With