Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 860
John K Avatar asked Mar 30 '26 18:03

John K


1 Answers

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

like image 73
Daniel Fischer Avatar answered Apr 02 '26 12:04

Daniel Fischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!