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
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With