Inconsistency with %hhu format specifier in C printf function?

672 views Asked by At

As far as I had understood it, the %hhu format specifier should have the range of an unsigned char. However, in some compilers I test it in, it seems to have the range of an unsigned short instead. Is there a reason for this?

I tried using %hhu to print, for instance, 65535. I would expect this to print 255 on the assumption the value would be cast to an unsigned char. However in CodeBlocks and Tiny C Compiler, I instead get 65535. If I instead try to print 65536, it prints 0, as I would have expected if I had instead used %hu (with one h).

In OnlineGDB, however, I get the behaviour I would have expected.

1

There are 1 answers

5
chux - Reinstate Monica On

With *printf(), "%hh":

... Specifies that a following b, d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); ... C23dr § 7.23.6.1 7

It is reasonable in suspecting an error when values outside the range of unsigned char are printed.

[Edit]

On-the-other-hand, "hh" is specified to use with a signed char or unsigned char argument. Since OP did not do that, the result is undefined behavior (UB).

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. § 7.23.6.1 9