# output of the programme

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

according to your code thre is 2 condition in the if statement, but if(i+=2)itâ€™s not even a condition. First do the incrmnt then check.

but this code is working perfectly for condition

if(i=i+5 )

giving output

True 4

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 2 && 0 is 0

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

[[ So Output was True 2. ]]

4 Likes

thnks buddy, i thnk u r ri8,but i hv one more problm.

If i change the code little bit ,like

if(i=i+2 && i==9)
then again , i==9 gives 0 first.and then 2&&0 give 0
then i=i+0 gives true value.So,the value must be printed is â€śYes 2â€ť
but it prints â€śNO 0â€ť. Plz can u explain this to me?

i dnt think bro,bcz here we are comparing 9 with i(i==9) not comparing 9 with 4. The && operation is performed on the result of i==9.
I thnk the explanation given below by rishabhprsd7 is correct. but agan we have one new problem,mention in my comment to rishabhprsd7

@prats_93

Sorry didnâ€™t had enough space in comment box to reply at your comment, So i am posting the explanation of next part here,

http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm

Here you can observe that + - (Unary plus/minus), has greater precedence than == which i didnâ€™t included in above screenshot.

So Now consider,

â€“> In condition, i=i+2 && i==9, â€ś+â€ť has highest precedence, so after addition operation exp will become,

â€“> i=4 && i==9, now comes i==9, as â€ś==â€ť has higher prece. than â€śâ€ť= and â€ś&&â€ť, that will again return 0

â€“> Exp. Becomes i=4 && 0. Then logical and â€ś&&â€ť has higher precedence than Assignment â€ś=â€ť

â€“> So 4 && 0 will be next condition which will return 0,

â€“> At last final expression will become i=0 and so 0 will be assigned to i

â€“> Now, I think since value of i is 0, if condition terminates, sending the control to else statement and thus final ans we get is,
false 0.

I think this would be the caseâ€¦

1 Like

if(i=i+2 && i==9) then again , i==9
gives 0 first.and then 2&&0 give 0
then i=i+0 gives true value.So,the
value must be printed is â€śYes 2â€ť but
it prints â€śNO 0â€ť. Plz can u explain
this to me?

It should be interpreted as if(i = (i + 2) && (i == 9))

so i == 9 gives 0 first.

(i + 2) && 0 gives 0.

So i = 0, so result is NO 0.

1 Like

okayâ€¦i got itâ€¦

3 Likes