2

For example such code may be useful:

unsigned char ch = 0xf2;
printf("%02hhx", ch);

However, ch is promoted to int when passing as a parameter of variadic function printf. So when %hhx is used, there is type mismatch. Is any undefined behavior involved here according to C standard? What if it is C++?

There are some discussion here but no answer is given.

user
  • 475
  • 3
  • 10
  • 1
    There is no type mismatch. The `hhx` code inside `printf()` converts the `int` to `unsigned char` and proceeds from there. – Jonathan Leffler Dec 07 '19 at 15:28
  • What "type mismatch" are you talking about? `printf` is perfectly aware of default argument promotions. And `%hhx` expects an `int` argument. `%hhx` affects the output spec only, but the argument it receives is still an `int`. – AnT stands with Russia Dec 07 '19 at 15:34
  • `ch` can be promoted to `unsigned int` when `UCHAR_MAX>INT_MAX`. This implies `sizeof(int)==1` and therefore it is not really promoted since on such a system `unsigned char` would be the same as `unsigned int`. – 12431234123412341234123 Sep 17 '20 at 11:17

1 Answers1

5

C11 standard says:

7.21.6.1/7 hh Specifies that a following 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); or that a following n conversion specifier applies to a pointer to a signed char argument.

So no, there is no undefined behavior. The standard is well aware that a char argument to a variadic function would be promoted to int.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85