Old said:
Well, you caused undefined behaviour by passing a
signed value. James' comment should be read as saying
it makes no difference to conforming code!
You are, of course, correct. I hadn't thought about it before,
but it makes perfect sense that %x takes an unsigned value.
(After all, I would want something like "8000" to display, and
not "-7fff".)
The %hx could in theory allow the compiler to optimize
more, as the printf implementation has the option of
discarding 2 of the 4 bytes read (say) before processing
them.
What does the standard say about a varadic function which gets
passed an int but reads it as short? Given that the standard
requires that (in this instance) a short be promoted to int
anyway, does passing an int invoke UB?
On a system with 16-bit short and 32-bit int, does this invoke
UB?
printf("%hd\n",65536);
My system displays zero, but "gives you the output you expect"
is allowed under UB.
Section 7.19.6.1p7 seems to allow it:
h Specifies that a following d, i, o, u, x, or X conversion
specifier applies to a short int or unsigned short int
argument (the argument will have been promoted according
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
to the integer promotions, but its value shall be
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
converted to short int or unsigned short int before
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
printing); or that a following n conversion specifier
^^^^^^^^
applies to a pointer to a short int argument.
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody |
www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net |
www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:
[email protected]>