Search code examples
cmacrosdirective

Macro Functions in C - Logic as argument?


I have encountered the following macro definition and I am trying to understand its use and its syntax and logic:

#define FOREACH(elem, list, body) {\
    for(size_t i = 0; i < size(list); ++i)\
    {\
        int elem;\
        if (get_elem(list, i, &value)) {\
            body\
        }\
    }\
}

I have come across macro functions before, however they were simpler and never included this much logic in them. What I did not understand mainly, what the body parameter is. Is it possible to pass in certain logic to be added to the function in place of the parameter name?

I didn't write this directive so I am not sure whether there are any errors in it.


Solution

  • Yes, you can pass arbitrary logic as body parameter. It will be pasted here:

         if (get_elem(list, i, &value)) {\
            body\
        }\