Is it 35 or 42??
#include
int main() {
int x=5;
printf("%d", x++ * ++x);
return 0;
}
Is it 35 or 42??
#include
int main() {
int x=5;
printf("%d", x++ * ++x);
return 0;
}
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Prasad RaveendranRank #320 · 7.8K reputationPosted Aug 23, 2023, 10:04 PM EDT
Since there's undefined behavior in this code due to modifying
xmultiple times without a sequence point, it's not guaranteed what the final output will be. The order of evaluation of sub-expressions is not well-defined, and the program might produce different results on different compilers or even with different optimization settings.In practice, you might get different outputs like 35 or 42 or any other unexpected value, or the program might crash altogether. It's essential to avoid writing code that relies on undefined behavior for consistent and predictable results.
Jayaprakash Lakshmanasamy24 reputationPosted Aug 24, 2023, 6:53 AM EDT
Thank you all. I checked on several sources, since it's underdefined the output may vary compiler to compiler. Most of the compilers gave output as 35.
From AI it's a different story. Both chat gpt and bard got confused ??, and giving different answers everytime. From chat GPT, I got 35 & 42. From Bard, I got 35 and 49.
Rajeev KumarRank #1,334 · 1.3K reputationPosted Aug 25, 2023, 12:51 AM EDT
According to me It would be 35, as its x++ is the post increment that firstly assign the value and after that incremented so x value is 5 and ++x is pre operator it firstly increamented x value is 6 but pre operator incremented x =x+1 so value is 7 .. so it would be 5*7 which is 35 and finally output is 35.
Cr BhargaviRank #420 · 5.9K reputationPosted Aug 24, 2023, 6:02 AM EDT
It would be 30, as its x++, the value of 5 will not change and will get change only in the next loop and ++x will be 6 because the incrementation happens at the starting and then the value would be used the same for the output. so it would be 5*6 which is 30 which is the output
Gurpreet AroraRank #327 · 7.6K reputationPosted Aug 26, 2023, 9:46 AM EDT
Output is 35
Mohammad HussainRank #513 · 4.8K reputationPosted Aug 24, 2023, 12:29 AM EDT
The output of the given program is 42.
Let's break down the expression step by step:
x++: The value of
x(which is 5) is used in the expression, and thenxis incremented by 1. So, after this operation,xbecomes 6.++x: Here,
xis incremented by 1, and then the incremented value (6) is used in the expression.Now, the expression becomes:
5 * 6, which equals 30.Therefore, the program will output
30.