Marcus Marcus - 3 months ago 24
C Question

C preprocessor macro for returning a string repeated a certain number of times

Does someone know of any C99 preprocessor magic that allows for creating a string consisting of another string repeated N times?


STRREP( "%s ", 3 )


"%s %s %s "

after preprocessing.

The only thing I could think of myself was something like this

#define STRREP( str, N ) STRREP_##N( str )
#define STRREP_0(str) ""
#define STRREP_1(str) str
#define STRREP_2(str) str str
#define STRREP_3(str) str str str

which works well, but is ugly as I have to define a macro for each repetition length manually. I want to use it together with variadic macros and the macro returning the number of macro arguments shown here.


My suggestion is to use the boost.


#include <stdio.h>
#include <boost/preprocessor/repetition/repeat.hpp>

#define Fold(z, n, text)  text

#define STRREP(str, n) BOOST_PP_REPEAT(n, Fold, str)

int main(){
    printf("%s\n", STRREP("%s ", 3));//STRREP("%s ", 3) -> "%s %s %s "
    return 0;