2

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

Giorgos Xou
  • 1,461
  • 1
  • 13
  • 32
Jacob
  • 23
  • 4
  • I forgot to add dots .... Thank you for noticing that! Now it's ready. I want to generate some C code with macros like in above – Jacob Nov 02 '21 at 00:09
  • I doubt there's a way to do this as you've outlined. I assume you've got a bunch of these comparisons you want to do, which is why you're trying to write this macro. What is the type of `arr[]`, and what kinds of things are you trying to compare? – Steve Summit Nov 02 '21 at 00:12
  • Yes, you're right, it's a typo. I've fixed it – Jacob Nov 02 '21 at 00:12
  • For string comparison. And also I want to learn how to use macros with auto generated indexes – Jacob Nov 02 '21 at 00:15
  • The array in `char []` – Jacob Nov 02 '21 at 00:16
  • `x`, `y` ,`z` ... - `char` – Jacob Nov 02 '21 at 00:19
  • Macros with a variable number of arguments are tricky, and somewhat limited, and I don't think they'll be able to do this. (I especially don't know how you'd auto-generate the indices.) I know it's not what you asked, but I would just use `strncmp` for this: `if(strncmp(arr, "xyz" == 0) { ... }` – Steve Summit Nov 02 '21 at 00:29
  • What is the actual problem you are trying to solve? Why do you need a macro that takes input character by character and what does that solve? – Lundin Nov 02 '21 at 10:28

2 Answers2

2

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).

H Walters
  • 2,634
  • 1
  • 11
  • 13
  • Thanks. I don't really think that thing is possible in pure C. But anyways, I'll use your preprocessor – Jacob Nov 02 '21 at 16:21
-1

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:

Giorgos Xou
  • 1,461
  • 1
  • 13
  • 32