Search code examples
cmacrosc-preprocessorcode-generation

How do I generate code like for using a C macro? #for?


Is there are C macro like the for loop, that can generate code for me to use functions?

for example:

I have

SetSystem1();
SetSystem2();
SetSystem3();
...
SetSystem100();

can I write

#for index = 0 to 100
    SetSystem##index();
#endfor

so the system will generate SetSystem1 to SetSystem100?

Is there are some macro can create code like this?

I can't use array pointer to the C library.


Solution

  • There is no such facility in the C preprocessor. Given the complexity of this tool and its shortcomings, there is no chance that it be extended in future versions of the C Standard.

    You can use another tool to generate the text and include that in your source file. Here is an example using the bash shell:

    for i in {1..100} ; do echo "    SetSystem$i();" ; done
    

    Alternately, using the tr utility:

    echo "SetSystem"{1..100}"();" | tr ' ' '\n'
    

    Or as commented by Eric Postpischil, using jot on BSD systems:

    jot -w '    SetSystem%d();' 100
    

    But KamilCuk found a simpler and most elegant solution:

    printf "    SetSystem%d();\n" {1..100}
    

    Advanced programmers' editors have powerful macro systems that will enable you to produce the same output interactively.