Marcus Marcus - 18 days ago 5
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?

E.g.

STRREP( "%s ", 3 )


becomes

"%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.

Answer

My suggestion is to use the boost.

E.g.

#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;
}
Comments