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.
CodePudding user response:
Is there are some macro can create code like this?
No, not really. Even if you want to create such macro, you have to spell out all possibilities - it will take 100 macros for 100 cases.
You can use libraries that come with such maros, like p99
https://gustedt.gitlabpages.inria.fr/p99/p99-html/group__preprocessor__for_gae3eb0e3a5216300874ed6cb9abc170ce.html#gae3eb0e3a5216300874ed6cb9abc170ce :
#define P00_SEP(NAME, I, REC, RES) REC; RES
#define P00_VASSIGN(NAME, X, I) SetSystem##I()
P99_FOR(A, 101, P00_SEP, P00_VASSIGN, , );
Or boost
https://www.boost.org/doc/libs/1_78_0/libs/preprocessor/doc/index.html :
#define DECL(z, I, text) SetSystem##I();
BOOST_PP_REPEAT_FROM_TO(1, 100, DECL, )
You can also use some external preprocessor additionally to C preprocessor. For example with m4
:
# forloop.m4, from documentation
divert(`-1')
# forloop(var, from, to, stmt)
define(`forloop',
`pushdef(`$1', `$2')_forloop(`$1', `$2', `$3', `$4')popdef(`$1')')
define(`_forloop',
`$4`'ifelse($1, `$3', ,
`define(`$1', incr($1))_forloop(`$1', `$2', `$3', `$4')')')
divert`'dnl
forloop(`i', `1', `100', `dnl
` SetSystem'i`();
'')
or with php:
<?php for ($i = 1; $i <= 100; $i ) echo "SystemOut".$i."();\n"; ?>
or with Python Jinja2:
{% for i in range(1, 100) %}
SystemOut{{ i }}();
{% endfor %}
CodePudding user response:
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.