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.

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

alt text

4 Likes

@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,

First Check this link :
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… :slight_smile:

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

but this code is working perfectly for condition

if(i=i+5 )

giving output

True 4

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

okay…i got it…

3 Likes