5

Why is "i" variable getting incremented twice in my program?

I modified the question but why is the output different. shouldn't it be same?.?

Code :-

#include<stdio.h>
#define MAX(x,y) (x)>(y)?(x):(y)
void main(void)
{
    int i = 10;
    int j = 5;
    int k = 0;
    k == MAX(i++, ++j);
    printf("%d %d %d",i,j,k);
}

Output :- 11 7 0

Shouldnt the output be 12 6 0

Community
  • 1
  • 1
Arijit Das
  • 55
  • 4

3 Answers3

5

Use braces around your macro definitions:

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

The expanded expression (with the original macro definition)

k == (i++)>(++j)?(i++):(++j);

groups as

(k == i++ > ++j) ? i++ : ++j;

i++ > ++j evaluates to 1, which is unequal to k (k is 0), so the third operand of ?: (++j) is evaluated. So, i is incremented once, j twice, and k wasn’t changed since its initialization, hence your output.

mafso
  • 5,433
  • 2
  • 19
  • 40
3

The problem is that the macro expands into this:

k == i++ > ++j ? i++ : ++j;

Operator precedence dictates that > has higher prio than == which has higher prio than ?: So the above is equivalent to this:

(k == (i++ > ++j)) ? i++ : ++j;

i++ and ++j are executed first. Since i++ > j++ gets evaluated to true (1), we get this:

(k == 1) ? i++ : ++j;

Then since k is 0, k == 1 is evaluated to false (0). We get:

0 ? i++ : ++j;

And therefore ++j is executed once more.


(As a side note, this expression is well-defined, because the conditional operator has a sequence point between the condition and the evauluation of the 2nd or 3rd operand.)

Lundin
  • 195,001
  • 40
  • 254
  • 396
2
k == MAX(i++, ++j);

is replaced as

k == (i++)>(++j)?(i++):(++j);

Here i=10,j=5. so

k == (10++)>(6)?(11++):(++6); 

so it that expression while checking condition i is incremented once after checking the condition due to post increment and j also incremented once. But 10 > 6 condition is true.

(k == 1 )?(i++):(++j); // here i=11 and j=6

(k == 1 )? (11++):(++6);

so here k==1 condition fails. it will not evaluate i++ in that expression, it will evaluate ++j and return it. here i is remains 11 and j become 7.

So you will get 11 7 0 as output.

Sathish
  • 3,740
  • 1
  • 17
  • 28