Thread: wat is the logic behind this?

1. wat is the logic behind this?

i=10; i=i++; printf("%d",i);

for the above part of the prog i got output 11.... y is it? wat is the logic?

2. Mmm...homework.

Think about it...it ain't rocket surgery. What would you have expected it to be, and why?

3. Originally Posted by vpshastry
i=10; i=i++; printf("%d",i);

for the above part of the prog i got output 11.... y is it? wat is the logic?
Why don't you tell us what you think each of the three parts are doing?

4. i expected the output to be 10, 1st is assigni 10 to i, 2nd is incrementin 'i' after assignin it to i, 3rd is print,,,,, o thought a lot abt it.... atill i'm not gettin

5. i expected 10 , bcz 'i'(RHS) gets incremented after assignin to 'i'( LHS)

6. Just break it up into steps:

Code:
```int i = 10;
i = i;
++i;
printf( "%d", i );```
Make sense?

7. Originally Posted by vpshastry
i expected the output to be 10, 1st is assigni 10 to i, 2nd is incrementin 'i' after assignin it to i, 3rd is print,,,,, o thought a lot abt it.... atill i'm not gettin
And that's where things are letting you down. Remember the right hand side is evaluated first and then assigned to whatever's on the left side of the equals sign.

Think about it, and consider that the following snippets are all going to do the same thing

i = i++;

i++;

i = i + 1;

etc.

8. The postfix operator '++' will allow 'i' to be assigned to itself and then it will increment it. Apparently it has a high precedence but it isn't actually incremented until last (C Operator Precedence Table).

9. you just claimed to know that 'i' was incrementing, and you still expect 'i' to equal the initial value, you're obviously lying or you don't know what the word 'increment' means.

i'll ask the question like this;

i = 10;
i = i(10) + 1

what is 10 + 1?

i = 10 + 1

i will give you a hint, 10 + 1 does not equal 10.

http://en.wikipedia.org/wiki/Increment

pop quiz:

i = 10
i++
++i

what's i?

10. Slightly off topic, but I keep forgetting... does i = i++; result in undefined behaviour? It does seem to trigger that, except that in all reasonable interpretations of the expression it is equivalent to a standalone i++ so the problem is more theoretical than practical.

11. its of course 12......

12. sry, i'm not fully satisfied with ur ans,,, i think both or not same in tat case...

13. Originally Posted by vpshastry
sry, i'm not fully satisfied with ur ans,,, i think both or not same in tat case...
What do you mean?

14. Laserlight is correct...it's classic undefined behavior. What happens is purely a consequence of what the compiler decides to do with it. See here for information on sequence points, which is pertinent to the discussion.

I apologize for my smart-ass answer in the beginning of the thread. Doing stupid things like i=i++ never crosses my mind, so I forget about it as being "undefined;" it simply makes no sense to do it in the first place.

15. i mean i=i++ can't be divided as i=i and ++i