John K
John K

Reputation: 31

Simple Macro Causes Compile Error

I'm attempting to define a macro that allows me to pass in 2 numbers as well as an operator. I want the macro to carry out the specified operation on the two numbers and return the result.

My definition is:

#define GENERAL_OP(x,y,op) ((x) op (y))

which works fine when I call

int result = GENERAL_OP(1, 2, -);

but as soon as I try to pass it a character (which is what I actually need to do in my generalized function that calls the macro) as in the following example:

void Evaluate(char op)...

int result = GENERAL_OP(1, 2, op);

Upvotes: 3

Views: 313

Answers (3)

Mike
Mike

Reputation: 49373

I see what you're going for... it's sort of like trying to unstringify. I'm pretty sure it can't work the way you want it to. Your best bet would be to do something like:

void Evaluate(char op, int x, int y)
{
    int result;
    if(op == '-')
      GENERAL_OP(x, y, -);
    ...

But that doesn't make it very "general"...

Upvotes: 0

md5
md5

Reputation: 23699

Preprocessor operates at compile-time, you can't use the value of op inside your macro.

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183858

void Evaluate(char op)...

int result = GENERAL_OP(1, 2, op);

Macro replacement is done before compile time, but the argument of Evaluate is only available at runtime, so the macro expansion leads to

int result = ((1) op (2));

there, and op is not a token that can appear there (probably an undeclared identifier).

Upvotes: 9

Related Questions