Reputation: 911
In my code I often have a for loop for doing a single operation n times. E.g:
// Wait for settle
int delayLoop = 0;
int count = 0;
for(delayLoop = 0; delayLoop < count; delayLoop++) {
__NOP(); // operation to do
}
At first I wanted to make this as an function....but then I realized I do not know how to pass in the operations as a function argument.
In the above example the __NOP()
is itself a macro that expands to:
__ASM volatile ("nop")
So how can I come up with a macro that I can call like this:
DO_LOOP(10, __NOP)
and what if I need to do more operations? e.g.
DO_LOOP(8, __NOP, myFunction(arg1))
that would expand to:
for(int i = 0; i < 8; i++) {
__NOP;
myFunction(arg1);
}
Upvotes: 0
Views: 350
Reputation: 97948
#define DO_LOOP(x, ...) for (int i = 0; i < x; ++i) { __VA_ARGS__; }
void f1() { printf("test\n"); }
void f2() { printf("a\n"); }
int main()
{
DO_LOOP(10, f1(), f2());
return 0;
}
gcc -E test.c
:
void f1() { printf("test\n"); }
void f2() { printf("a\n"); }
int main()
{
for (int i = 0; i < 10; ++i) { f1(), f2(); };
return 0;
}
This doesn't work with inline assembly though. You can do something like:
#define DO2(x, a, b) for (int i = 0; i < x; ++i) { a; b;}
and use:
DO2(10, __NOP(), f1());
Upvotes: 1