DEV Community

Discussion on: Repeat macro in C?

Collapse
 
omercsp profile image
Omer • Edited

I don't want to be rude, but this isn't the way to tackle such tasks.
Macros are great, and can be extremely helpful when inlining some code or do rather complex operations on arbitrary variable types (in C; C++ has also templates for this job) and can be helpful in other places, but in general, you want to avoid using them for tasks like repeat - they are harder to program and much harder to debug. Another problem here is that the both C and generated machine code are bloated (though the compiler might optimize the latter. And lastly, this approach limits the user to the max repeats the REPEAT macro author has used (in our case - you).

Hence a somewhat more robust and simple solution is due:

#include <stdio.h>  

void my_printf(int n)
{
    printf("%d\n", n);
}

typedef void (*my_printf_t)(int);
void repeat(my_printf_t fn, int n)
{
    for (int i = 0; i < n; i++)
        fn(i);
}

int main()
{
    repeat(my_printf, 10);
}

Enter fullscreen mode Exit fullscreen mode

This solution can be both easily extended to have any function even such retrieved dynamically on runtime. Also note there's no limitation to the number of repeats. This example is very simplified, as, like the original question, it is limited to to functions with a single integer parameter (rpeating things isn't really a problem, is it? this is what loops are for), but it's enough for the point I'm trying to make. It can be used a basis for cases where this sort of programming style is actually helpful.

If we must use macros (and for discussion reference), the following snippet is, again, much shorter and with no 100 (or whatever) limit:

#define PRINTF(N) printf("%d\n", N);
#define REPEAT(FN, N) \
do \
{ \
    for (int i = 0; i < N; i++) \
    { \
        FN(i); \
    } \
} while (0)


void solution_with_macros()
{
    REPEAT(PRINTF, 50);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sgf4 profile image
Horu • Edited

I understand your point but I made this repeat macro for repeating exactly the code using the preprocessor, this example wouldn't be useful if you want to use this out of functions, for example you wouldn't be able to create 10 functions using your repeat macro.