# if/else simple c programme

Explain the output of this program.

``````#include<stdio.h>
main()
{
int i=2;
if(i+=2 && i==9)
printf("true %d ",i);
else
printf("false %d ",i);
}
``````

Excepted output:
False 4

Actual output:
True 2

1 Like

Iâ€™m not so good in C/C++, probably something with operator prioritiesâ€¦

When I modified a code little bit

``````#include<stdio.h>
main()
{
int i=2;
if ( (i+=2) && (i==9) )
printf("true %d ",i);
else
printf("false %d ",i);
}
``````

Iâ€™m getting `false 4`â€¦

1 Like

if i take if statement as "if(i= i+2 && i==9)

then the output is coming as false 0

3 Likes

okayâ€¦now i am guessing somethingâ€¦

lets startâ€¦

first the compiler will take i+=2;

then i will be equal to 4â€¦

then it will consider the bitwise AND operator â€ś&&â€ť with â€ś9â€ťâ€¦

ans bitwise AND operator of "4 AND 9 " is equal to 1â€¦

thus if statement will work as it has if(1)â€¦(1 in it)â€¦

ans thus it will print true 2â€¦

like it if you agreeâ€¦ -_- â€¦

3 Likes

Okay i got itâ€¦
Since == has higher precedence,

â€“> i==9 wil return 0

â€“> Then comes && with precedence higher than +=, so 0 && 2 is 0

â€“> and at last i+=0 is i itself;

[[ So Output was True 2. ]]

3 Likes

@rishabprsd7
Thanks for explaining it.I was taking the expression separately. I was wrong there:)
Have been thinking for long,but then finally got that.Thank you!!

i know thatâ€¦ but my question is different

but i+=2 means same as i = i+2â€¦
isnâ€™t itâ€¦???

3 Likes

@rishabhprsd7
Why is the last step i+=0,instead it is i+=2?After the if statement,i will become 4.(i==9) just comparing,it wonâ€™t change i to 0.

so 0 && 2 is 0

exactly bro,thts i want to know that ,if both are same ,then y the answer is differentâ€¦

@ansh1star033

exp: i+=2 && i==9

According to operator precedence, == has highest precedence, So

Remains unoperated: (i+=2 &&), First opt. : i==9 which will return 0,

Now,

Exp becomes i+=2 && 0, As && has highest precedence,

Remains unoperated: (i+=), Second Opt, : 2 && 0 which will return 0 again,

Exp becomes i+=0, and now += has precedence, (only left operator in exp), So exp becomes i=i+0 and so i=i thus value of i is itself, i.e. 2.