0

How to fix the macro expansion issue below ?

#define GET_VAL                        3,2
#define ADD_VAL(val0, val1)            ((val0) + (val1))

void foo()
{
    int res = ADD_VAL(GET_VAL);
}

The macro is getting expanded as below and resulting in an error. I am using MSVC 2019

res = 3,2 + ;

I even tried using a helper macro as below, but still getting the same error.

#define GET_VAL                  3,2
#define ADD_VAL1(val0, val1)     (val0 + val1)
#define ADD_VAL(val)             ADD_VAL1(val)

Expecting expansion: ADD_VAL(GET_VAL); --> ADD_VAL(3, 2); --> 3 + 2

4
  • 2
    Your question is inconsistent. The first example should result in ptr appearing in the expansion. Your second example should produce the expansion you expect, what error did you get? Commented Jan 19, 2023 at 5:43
  • 2
    As @DanBonachea said, your second example should normally work. coliru.stacked-crooked.com/a/de420577039f7e7b Commented Jan 19, 2023 at 5:58
  • 1
    Can you elaborate on your goals? The C preprocessor can be abused in horrible ways for code obfuscation but why else?
    – chqrlie
    Commented Jan 19, 2023 at 6:18
  • I even tried using a helper macro as below, but still getting the same error. What error? Expecting expansion: ADD_VAL(GET_VAL); --> ADD_VAL(3, 2); --> 3 + 2 And I am also expecting this expansion with another pass, this is what should happen.
    – KamilCuk
    Commented Jan 19, 2023 at 8:19

2 Answers 2

2

By default msvc doesn't use a standard confirming preprocessor implementation, make sure to enable it with /Zc:preprocessor

Macros fully expand their arguments in isolation before pasting them into the replacement text, but the resulting tokens aren't separated into a new argument list. They way to fix your behavior is to create an intermediate macro that expands the arguments, and passes the expanded arguments to your macro:

#define GET_VAL 1,2
#define ADD_VAL(...) ADD_VAL_(__VA_ARGS__)
#define ADD_VAL_(a,b) ((a)+(b))
ADD_VAL(GET_VAL) // should work now

Another option is to write a fx macro that evaluates arguments and applies a function to them:

#define FX(f,...) f(__VA_ARGS__)
#define ADD_VAL(a,b) ((a)+(b))
FX(ADD_VAL,GET_VAL) // should work now
-1

C preprocessor can be abused in horrible ways

#define GET_VAL                3,2
// #define ADD_VAL(val0, val1)    ((val0) + (val1))
#define ADD_VAL(val)       ((int [2]){val}[0] + (int [2]){val}[1])

int main() {
  printf("%d\n",ADD_VAL(GET_VAL));
}

Output

5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.