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?
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?
Mmm...homework.
Think about it...it ain't rocket surgery. What would you have expected it to be, and why?
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
i expected 10 , bcz 'i'(RHS) gets incremented after assignin to 'i'( LHS)
Just break it up into steps:
Make sense?Code:int i = 10; i = i; ++i; printf( "%d", i );
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.
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).
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
read^
pop quiz:
i = 10
i++
++i
what's i?
Last edited by since; 11-18-2009 at 12:47 PM.
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
its of course 12......
sry, i'm not fully satisfied with ur ans,,, i think both or not same in tat case...
What do you mean?Originally Posted by vpshastry
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-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.
i mean i=i++ can't be divided as i=i and ++i