user25108
user25108

Reputation: 393

Understanding side effect in #define usage

I am referring to this question

#define max(a,b) ((a<b)?b:a)

this will have a some side effect as stated in the answer;

The side effects appear if you use max(a++,b++) for example (a or b will be incremented twice)

I am not able to understand this side effect; why a or b will be incremented twice when we use max(a++,b++) ?

Upvotes: 1

Views: 89

Answers (2)

yasouser
yasouser

Reputation: 5187

max(a++, b++) will be expanded as ((a++ < b++) ? b++ : a++). While evaluating from the left the expression (a++ < b++) get precedence and will increment both a and b. This is the first increment. Then depending the output of < operator, either a or b will get incremented again (this is the second increment).

Upvotes: 1

user1814023
user1814023

Reputation:

If you use max(a++,b++) in your code like this,

x = max(a++,b++);

a text replacement happens as

x = ((a++<b++)? b++ : a++);
      ^   ^     ^---------Increment if condition is true
      |---|---------Increment

So you will be incrementing either a or b twice...

Upvotes: 7

Related Questions