Although you are explicitly allowed to use the va_arg
macro from <stdarg.h>
to retrieve a parameter that was passed as an unsigned
as an int
(7.15.1.1/2), in the documentation for fprintf
(7.19.6.1/9) which also applies to printf
, it explicitly states that if any argument is not the correct type for the format specifier - for an unmodified %d
, that is int
- then the behaviour is not defined.
As @bdonlan notes in a comment, if the value of b
(in this case 2^N - 1
for some N
) is not representable in an int
then it would be undefined behavior to attempt to access the value as an int
using va_arg
in any case. This would only work on platforms where the representation of an unsigned
used at least one padding bit where the corresponding int
representation had a sign bit.
Even in the case where the value of (unsigned)-1
can be represented in an int
, I still read this as being technically undefined behavior. As part of the implementation, it would seem to be allowed for an implementation to use built in magic instead of va_args
to access the parameters to printf
and if you pass something as an unsigned
where an int
is required then you have technically violated the contract for printf
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…