4

Another way to phrase this question might be "How to end format specifiers in printf"

If I want to print microseconds in this format 100us using the following code...

long microseconds = 100L;
printf("%lus", microseconds);

only prints 100s because the u is combined with the %l and it interprets the format specifier as an unsigned long instead of a long

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
baconcheese113
  • 843
  • 2
  • 13
  • 27
  • 7
    `%l` is not a complete format specification by itself. It might work by accident on some C libraries but it's incorrect to rely on that. Always give complete format specifications (in this case you wanted `%ld`) and you won't have this problem. – zwol Sep 04 '22 at 18:49
  • @zwol ah, noticed that after posting. The question is more in general, since I'm sure there are other cases where a conflict can occur. I'll try to find a different example – baconcheese113 Sep 04 '22 at 18:53
  • 1
    The answer for the general case is the same: all conversion specifications must end with one of the "conversion specifier" characters (comprehensive list here: http://port70.net/~nsz/c/c11/n1570.html#7.21.6.1p8) You will not have a conflict with subsequent text if you make sure always to do that. Also, `printf` may crash or print nonsense if you don't always do that. I can make that a proper answer later when I'm on a real computer. – zwol Sep 04 '22 at 19:02
  • @zwol I think my confusion came from not realizing that every format specifier has to end with a single conversion specifier symbol/character. And then also mixing up some of the conversion specifiers with other modifiers. Thanks for helping me clear up my confusion! – baconcheese113 Sep 04 '22 at 19:12
  • Note the `L` in `100L` serves little purpose. – chux - Reinstate Monica Sep 04 '22 at 21:55

2 Answers2

6

Just write

long microseconds = 100L;
printf("%ldus", microseconds);

Pay attention to that you may not use a length modifier without a conversion specifier.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

How to separate format specifiers from characters with printf

If separation is important:

long microseconds = 100L;
printf("%ld" "us", microseconds);

Adjacent literal strings are concatenated. The above is equivalent to "%ldus".

// or maybe via macros
#DEFINE TIME_FMT "%ld"
#DEFINE TIME_SUFFIX "us"
...
printf(TIME_FMT TIME_SUFFIX, microseconds);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256