0

How is the output of this C program 9 and not 8?

#include <stdio.h> int main(){ int x=3,y; y=(++x)+(x++); printf("%d",y); return 0; } The reason why i think 8 was the correct answer: The pre-increment operator ++i is evaluated first. It increments the value of i to 4 and returns the new value, which is used in the addition. So the expression now becomes 4 + (i++). Next, the value of i is 4, so the post-increment operator i++ returns the current value of i, which is 4, and then increments i to 5. (but the current value is 4) So the expression now becomes 4 + 4. The addition is performed, and the result is 8.

10th Apr 2023, 5:16 PM
Draken
Draken - avatar
1 Resposta
+ 5
Unfortunately, it is not that easy. To understand the output of your program, you must understand "sequence points". In a nutshell and our purpose here, sequence points are points in the code where all side effects, such as pre- and postincrements, are resolved. In between sequence points, the designers of C compilers are free to order the underlying CPU instructions anyway they like. In the expression (++x)+(x++) there is no sequence point. The order of effect of the increments is undetermined. And for that reason, said expression results in undefined behaviour. Don't try to argue why a value should result and others not. It is a moot point to argue. It is undefined behaviour. Period.
10th Apr 2023, 6:09 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar