5

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

5
  • 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
    Commented Sep 4, 2022 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 Commented Sep 4, 2022 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: 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
    Commented Sep 4, 2022 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! Commented Sep 4, 2022 at 19:12
  • Note the L in 100L serves little purpose.
    – chux
    Commented Sep 4, 2022 at 21:55

2 Answers 2

6

Just write

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

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

1
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);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.