1

What are the shortening length modifiers (i.e., h, hh) in the *printf* function family for?

What's wrong printing shorter integers as ints ("%d") or unsigneds ("%u") given that that's how they'll be passed in anyway?

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 2
    Opinion based. But there might be subtle differences on certain platforms (e.g. with other than 2's complement integers). And symmetry with `scanf` (where they are obviously needed) might also be an aspect. – too honest for this site Jan 07 '17 at 13:15
  • One more: they allow a platform to use optimised code. For an 8-bit CPU e.g. it is easier to div/mod an 8-bit `char` instead of a full-sized (typically 16 bit) `int`. Similar for more exotic architectures possibly. – too honest for this site Jan 07 '17 at 13:19
  • 2
    When I've considered the question before, symmetry with `scanf()` -- to the point of sharing format strings for input and output -- was the best I could come up with. – John Bollinger Jan 07 '17 at 13:19
  • @JohnBollinger: On >=16 bit plaforms you might be correct. But on small 8 bit CPUs optimised conversion functions will safe a lot of run-time (at the cost of space). – too honest for this site Jan 07 '17 at 13:23
  • 1
    Try printing the value of `signed char c = -1;` using `"x"`. – alk Jan 07 '17 at 13:26
  • @pskocik: sry, meant x not d. – alk Jan 07 '17 at 13:30
  • @alk Thanks. That's a very good point, although it's easily handled by passing `(unsigned char)c`. – Petr Skocik Jan 07 '17 at 13:33
  • @PSkocik: I doubt the cast helped. Did you try this? – alk Jan 07 '17 at 13:36
  • @alk It works well. I believe casting chars to uchars and shorts to ushorts before printing them as %x or %u will always do the job of the h or hh length modifiers. – Petr Skocik Jan 07 '17 at 13:50

0 Answers0