Can you explain the output! | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
14th May 2019, 6:07 AM
Punnam Ruthvik Reddy
6 Réponses
+ 5
The operations in the printf 'slots' are evaluated from right to left. Only in case of a postfix, the value in that printf slot is determined right then. So ++x increases x to 3, but doesn't settle the last slot because it's prefix. Next, x++ sets the value to 4, but before (postfix), the slot is set to the former value 3. This happens again in the first slot, so 4 is left in the slot, then x incremented. Finally, now that all postfixes are settled, the prefix expression in the last slot gets the final value of x. Questions like these come up a lot here, but the most important thing to remember about this is that we shouldn't write code like that, because depending on the compiler, the result might be different (undefined behaviour). If you change the value of a variable in the middle of a statement, this variable should occur only this one time in that statement.
14th May 2019, 7:03 AM
HonFu
HonFu - avatar
+ 5
There is nothing to explain, the output is indefinite, output in one compiler will be different with that of another, as HonFu said, undefined behaviour. You might consider this article about sequence points: I'm still struggling to understand it so I shouldn't try to explain, I'd only make things worse : ) http://c-faq.com/expr/seqpoints.html
14th May 2019, 7:07 AM
Ipang
+ 2
I found this phenomenon interesting so I tested it and can confirm HonFu's explanation. But I had to realy play the scenario through to grasp the concept completely. So the Statement is evaluated from right to left where the post fix increment puts out x's current value and then increments x and the prefix increments x but waits with outputing x's current and final value (reference type) until last. Thus it must go something like this: 0. x++,++x, ++x // x=2 1. x++,++x, ++(2)=x // x=3 2. x++, ++(3)=x, x // x=4 3. (4)++=4, x, x // x=5 4. 4, 5, 5 0. x++,x++, ++x // x=2 1. x++,x++, ++(2)=x // x=3 2. x++, (3)++=3, x // x=4 3. (4)++=4, 3, x // x=5 4. 4, 3, 5 ++x,++x,++x // 555 ++x,++x,x++ // 552 ++x,x++,++x // 535 ++x,x++,x++ // 532 x++,++x,++x // 455 x++,++x,x++ // 452 x++,x++,++x // 435 x++,x++,x++ // 432
15th May 2019, 7:08 AM
Michael U.
Michael U. - avatar
+ 2
Is it 235?
17th May 2019, 3:04 PM
Ais
Ais - avatar
+ 1
@Robin My head is spinning but thank you. :) As far as i could read the output, CLANG would put out something quite different: 2,3,5 instead of 4,3,5? So my conclusion for now will be that I ought not touch that stuff even with a long stick. ;)
15th May 2019, 10:24 AM
Michael U.
Michael U. - avatar
+ 1
Thank you Robin. I will try to remember to try and to ask when I hit a wall while doing so. :)
15th May 2019, 6:41 PM
Michael U.
Michael U. - avatar