Numerator
Numerator

Reputation: 1409

Defining a macro in C

Lets say I define a macro:

#define MAX(x,y)    ((x)>(y)?(x):(y))

What would happen if I call MAX(I++,J++)?

I couldn't understand why the answer would not be as expected.

Upvotes: 0

Views: 449

Answers (3)

fduff
fduff

Reputation: 3811

in int res = MAX(x,y); the macro will expend to

(((x) > (y)) ? (x):(y));

now if x = a++ and y = b++ that will translate into

(((a++) > (b++)) ? (res = a++):(res = b++));

thus, for the path where the condition is true, whichever variable it is will be inc twice in total but the resulting value stored in res will have only one increment (as you're using post incrementation).

It can be tricky to use post-inc in function/macro calls as they can introduce subtle logic glitches.

Prefer passing the variable to a function/macro as is and do whatever change to it separatly, that will save you time on that kind of issues.

Upvotes: 1

Emil Vikström
Emil Vikström

Reputation: 91942

Macros are just for the preprocessor. This is what would get compiled by the C compiler:

(((I++)>(J++))? ((I++):(J++)))

As you can see, if I is larger than J then I will get incremented twice and J once, otherwise it's vice versa.


Your macro is not even correct. The outer layer of parentheses is wrong here, which will cause a compilation error:

((I++):(J++))

Upvotes: 6

James M
James M

Reputation: 16718

MAX(I++,J++) would expand to (((I++)>(J++))? ((I++):(J++))). Notice there are two occurrences of I++ and J++, so they would both be incremented after the comparison, and then whichever is the result would be incremented again.

You could use an inline function instead:

inline int MAX(int x, int y)
{
    return x > y ? x : y;
}

But I suppose the macro has the advantage of working for any type.

Upvotes: 2

Related Questions