Home > database >  How do I create an expression using macros in C?
How do I create an expression using macros in C?

Time:11-03

I need a macro that takes input as

MACRO(x, y, z, ...)

and expands to

arr[0] == x && arr[1] == y && arr[2] == z ...

Any ideas?

arr is char[], and macro args are single chars

CodePudding user response:

Using boost preprocessor:

#include <boost/preprocessor.hpp>

#define MACRO_AND(Z, N_, ARGS_)  \
    BOOST_PP_EXPR_IF(N_, &&) \
    arr[N_] == BOOST_PP_TUPLE_ELEM(N_, ARGS_)

#define MACRO(...) \
    BOOST_PP_REPEAT( \
        BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), \
        MACRO_AND, \
        (__VA_ARGS__))

This uses BOOST_PP_REPEAT to iterate the variadic arguments, feeding them in as a tuple via the data parameter. BOOST_PP_EXPR_IF prefixes the && for all but the 0th argument.

Boost preprocessor is a header only library and can be used with C.

Demo (on coliru) here.

FYI, be very careful... I'm not sure how you're going to use this for generic string inputs (e.g. if the NUL terminator comes up during the comparison).

CodePudding user response:

How about this:

#define MAKE_MACRO(arrname,x,y,z) (arrname)[0] == x && (arrname)[1] == y && (arrname)[2] == z
#define MACRO(arrname,x,y,z) MAKE_MACRO(arrname,x,y,z)
int main()
{
    char arr[3] = {'a','b','c'};
    
    if (MACRO(arr,'a','b','c'))
        printf("TRUE");
    else
        printf("FALSE");
        
    return 0;
}

Useful Referecnes:

  • Related