How to separate format specifiers from characters with printf

Viewed 85

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

2 Answers

Just write

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

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

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