Search code examples
cdataformat

Reuse a format specifier in C


Is there a way to reuse a format specifier in C? I would like to use the same specifier for the next 20 outputs, is there an easier way than to write the specifier 20 times? v

In Fortran I can do this by writing 20 in front of the specifier, so (20F10.0) would be the same as (F10.0 F10.0 F10.0...). Is there something similar in C?


Solution

  • At the risk of your preprocessor macros looking like a snake with a severe stutter and your future self wondering why on earth you've done something like this, you could (ab)use the fact that string constants can be concatenated...

    #include <stdio.h>
    
    #define REPEAT5(s) s s s s s 
    #define REPEAT4(s) s s s s
    #define REPEAT20(s) REPEAT4(REPEAT5(s))
    
    int main() {
        printf(REPEAT20("%d "), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
    }
    

    If you run this on Godbolt.org you can see the format string was correctly expanded to

    .asciz  "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d "