Search code examples
cmacrosx-macros

Can any one explain about X-macros with example code to use them?


I am trying to understand the X-macros topic in detail. But didn't get the full clarity on this. It would be better if any one of the expert will explain this topic with some example "how to use, how to call."

I have found several articles, but didn't get the full clarity on this. In all places, they have used pieces of code where i am lacking in using of those X-macros.

Thanks in advance Partha


Solution

  • You basically #define a list of variables as parameters to an place holder macro X:

    #define X_LIST_OF_VARS \
        X(my_first_var) \
        X(another_variable) \
        X(and_another_one)
    

    You then use the template:

    #define X(var) do something with var ...
    X_LIST_OF_VARS
    #undefine X
    

    to make code blocks. For example to print all your vars:

    #define X(var) printf("%d\n", var);
    X_LIST_OF_VARS
    #undefine X
    

    will generate:

    printf("%d\n", my_first_var);
    printf("%d\n", another_variable);
    printf("%d\n", and_another_one);