+ 5
My concept is wrong or my compiler is not working properly?
According to my concept, the following program should give 36 as output (13+12+11=36). But the compiler is showing 37 as output. where I am wrong? please help me. Even I tested in my Linux operating system (Ubuntu 16.04) and it also shows 37. #include <stdio.h> int main() { int x=10; printf("%d",++x + ++x + ++x); return 0; }
5 Réponses
+ 2
@Hatsy Rei, this UB case is annoyingly common in the quizzes ;) :
https://ibb.co/noU8e6
See also:
https://code.sololearn.com/cBg3yJKuyCM9/?ref=app
+ 2
@Hatsy Rei, I didn't get it, can you please explain me in simple words.
+ 1
Saurabh Verma, Here's one similar question:
https://www.sololearn.com/Discuss/957040/what-is-the-output-of-the-code
Read the answers, and click the links in the answers for more info.
In your case, there's no evaluation order defined for (++x + ++x + ++x) and it is evaluated in one sequence point. The ++x operation even may be evaluated in parallel. For general rule of thumb, remember what operators do and what don't create a sequence point, and don't modify any variable more then once in one sequence point.
+ 1
Your code could increment x to 13 first. Add 3 13's to print 39. Increment 10 to 11 3 times and add to get 33. And every number in between could be generated depending on the compiler's choice of execution. Because the standard doesn't define how to process your code, instead it states it is undefined behavior and leaves it to the compiler to whatever it picks. Personally, the standard should have defined it as illegal.