Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is “i” variable not getting incremented twice in my program?

Tags:

c

macros

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

like image 994
Arijit Das Avatar asked Aug 08 '14 10:08

Arijit Das


3 Answers

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.

like image 58
mafso Avatar answered Sep 20 '22 15:09

mafso


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

like image 22
Lundin Avatar answered Sep 18 '22 15:09

Lundin


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.

like image 23
Sathish Avatar answered Sep 19 '22 15:09

Sathish