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

i know that… but my question is different

but i+=2 means same as i = i+2…
isn’t it…???

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

alt text

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.

read the previous step…

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.

Sorry for Bad English…!!

1 Like

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

welcome… :slight_smile: