Home > Mobile >  How I can define a macro that replaces the name of a variable with its own value?
How I can define a macro that replaces the name of a variable with its own value?

Time:01-21

I will like to have a macro that works like this

int a = 20;
int b = 21;
EXPAND(a == b); // prints 20 == 21

Is this possible with c ?

The only thing I can think of how to do something like this is with a macro like this:

EQUALS(a, b);

In this case is very easy to compose a string with the values of the variables, but I was wondering how I will be able to replace the == with a comma

CodePudding user response:

Nothing in the preprocessor allows you to cut the token sequence a == b into separate token sequences for general identifiers a and b, even if you limit yourself otherwise to this form.

If you limit yourself to a selected set of identifiers you could implement it using the ## token concatenation operator and rescanning of the expanded macro, but that is unlikely to be what you want.


On the language level you can do a bit of trickery, for example you can make use of the operator precedence and/or associativity to expand the macro in such a way that == isn't actually evaluated between a and b, e.g.

#define EXPAND(expr) (MyClass{} < expr).eval();

Now if a == b is expanded, then you will actually end up with the expression (MyClass{} < a) == b. MyClass{} can then have all comparison operators overloaded and reconstruct the actual expression internally, then evaluate/print it in the eval member function.

This approach is not going to work with variable names in nested expressions or if there are parentheses around the test.

This also seems to be what e.g. Catch2 does, but I guess there are other more less useful tricks as well.


I would however suggest simply getting rid of the macro and replacing it with a simple function call like printEquals(a, b);. That's much simpler to implement as a function template and doesn't require using a macro.

  •  Tags:  
  • c
  • Related