The following program has undefined behavior:
#include <stdio.h>
int main(void)
{
unsigned int x = -100; // This is fine, becomes UINT_MAX - 100
printf("%d\n", x); // This is undefined behavior.
return 0;
}
C99 7.19.6.1p8 states %d expects an int argument.
C99 7.19.6.1p9 states "If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."
However, gcc -Wformat
(which is included with -Wall
) will not complain about the above program, why? Is this a bug, or a deliberate omission?
From the gcc manpage:
-Wformat
Check calls to "printf"
and "scanf"
, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense
x
(anunsigned int
object) is interpreted as if it were of typeint
. – Prickingva_arg
macro. – Potboilerint
, the call would be legal. So why should gcc be expected to issue a warning for a legal case? – Naganox
exceedsINT_MAX
, the behavior is undefined. Arguments of typeint
andunsigned int
are interchangeable only for values representable in both types. – Prickingva_arg
. Since the standard doesn't specify the behavior in anyway other than through unsigned to signed conversion, I concluded implementation defined via that conversion. But, YMMV. – PotboilerUINT_MAX-100
exceedsINT_MAX
. And the section says nothing about conversions. – Pricking