+ 3
Why does ++a + ++a gives different answer in C++?
So I tried this simple block int a = 3; cout << ++a + ++a; I tried it in different compilers and I got 9 in some and 10 in the others. 9 seemed justified to me, but I could not wrap my head around why this gives 10. Please help.
19 ответов
+ 8
I am not sure if they are using different precedence rule .. it does seem like UB im not completely sure why .....
ChillPill 🌶 sir ?
Clang gives 9
and gcc gives 10
for clang it works like so
(++a) + (++a) //9
for gcc its like this
(++(a++))+a //10
https://en.cppreference.com/w/cpp/language/operator_precedence
Clang ones seem like its wrong as postfix has more precedence....
Personal suggestion : never modify one variable twice in a single expression like this ....
+ 7
I'm pretty sure that it is undefined behavior in the standard definition of the language, so the result is compiler-dependent.
+ 6
It seems to depend on programming language, version/standard.
https://stackoverflow.com/questions/14798953/why-are-multiple-increments-decrements-valid-in-c-but-not-in-c
+ 5
Not a direct answer to the question, but you might be interested in this thread as well:
https://www.sololearn.com/Discuss/2882645/?ref=app
+ 4
In c/c++, when the statement have sequence point issue then it produce side effects and the output is compiler dependent , because it is undefined by standards..
https://en.m.wikipedia.org/wiki/Sequence_point
So it may evaluated as 4+5 or 5+5 or 5+4 Or
++(3+4) depends on compiler implementation..
edit:
additionally :
https://stackoverflow.com/questions/7721383/on-c-c-basically-what-things-are-compiler-dependent
+ 2
Yeah a month ago I was also stuck with same.
Can you list me the compilers which gave you output 10.
+ 2
Snehil Pandey SoloLearn also gives 10 and the interview bit and programiz compiler gives 10. The g++ that I use also gives 10 as output
+ 2
rust wins again amiright ChillPill 🌶 ?
+ 2
ChillPill 🌶 of course, this is not the place for such debates. i was merely joking.
+ 2
ChillPill 🌶 looks like i passed the flags -Wrustacean -Wdefend ...
+ 1
Prashanth Kumar you are invited to solve this issue
+ 1
Prashanth Kumar Okay, thanks for clearing that out!
+ 1
Depends on the compiler. Follow the one which follows fundamental concepts. Or you can put brackets in order to make it follow
0
a=3
++a=4
+
++a=5
=9
Different compilers may give different outputs but by programming logic, the answer should be 9.
0
(++a) + (++a) is much safer
0
The difference lies in which value is used in the rest of the expression containing it. With ++a, a is incremented first, and that is the value you get; with a++ you get the value of a, and a is incremented afterwards.