Reputation: 305
What's happening in this macro? I understand that #test expand this parameter to the literal text. But what does pre;
and test;
do?
#define MACRO_FN(test, pre, repeat, size) \
do { \
printf("%s: ", #test); \
for (int i = 0; i < repeat; i++) { \
pre; \
test; \
} \
} while (0)
This is used like so
MACRO_FN(a_func(an_array, size),, var1, size);
What do the double commas mean here?
Upvotes: 0
Views: 412
Reputation: 50778
Here is a minimal example:
#define repeat 5 // I added this, because 'repeat' is not mentionned in your question
#define MACRO_FN(test, pre, var1, size) \
do { \
printf("%s: ", #test); \
for (int i = 0; i < repeat; i++) { \
pre; \
test; \
} \
} while (0)
void foo()
{
}
void func(int a, int b)
{
}
int main()
{
MACRO_FN(func(2, 3), foo(), var1, size);
}
Once preprocessed, the code is equivalent to this:
int main()
{
printf("%s: ", "func(2,3)");
for (int i = 0; i < 5; i++)
{
foo();
func(2, 3);
}
}
So that macro is a wrapper that prints the function name plus it's parameters as it is invoked with the macro and executes that function specified in the first parameter repeat
times (whatever repeat
is). If the second parameter is omitted, the function that has that name is simple not invoked before the function mentioned before as in the following example:
int main()
{
MACRO_FN(func(2, 3),, var1, size);
}
Once preprocessed, the code is equivalent to this:
int main()
{
printf("%s: ", "func(2,3)");
for (int i = 0; i < 5; i++)
{
;
func(2, 3);
}
}
Note:
I removed the do while(0)
from the equivalent programs for brevity, read this SO article for more information:
Upvotes: 3
Reputation: 54
pre
and test
seem to be two functions.
Based on how it is written, we can guess that pre
is a function called before the test
.
The double comma has no special meaning. It is just here because the second parameter (pre
) was omitted.
Edit: As a side note that kind of macro "should be avoided like plague", as @Lundin put it.
Upvotes: 3