0
b = a++ * ++a ?
hi , so i just started C++ and have question. i almost know the difference between a++ and ++a ,but have a problem in solving this : int a = 2; int b = a++ * ++a; cout<<a; cout<<b; i have no idea how a will be 4 and b will be 8 .can someone explain it to me pls ?
5 Antworten
+ 3
Having an expression which modifies a variable more than once in a single sequence point* results in undefined behavior. This means that there is no guarantee that b will be 8.
https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points/4183735#4183735
*Even in later revisions of C++, where sequence points have been replaced, it remains undefined behavior due to the combination of side effects and the unsequenced nature of the expression.
In fact, this has been discussed multiple times over the past few years in SL
https://www.sololearn.com/discuss/2470770/
https://www.sololearn.com/discuss/527482/
+ 1
Let's work through it...
a = 2
Now look at the part on the right side of the assignment (a++ * ++a). We know this works left-right (operator precedence, link at bottom).
The first side:
a++
This is saying, take 'a' and then increment it, so the value of 'a' is taken as 2, the variable 'a' is then incremented to 3.
The second side:
++a
Now 'a' is 3, as this is prefix this is incremented and to the value of 4.
Then it's simple math 2 x 4.
Operator precedence: https://en.cppreference.com/w/cpp/language/operator_precedence
+ 1
changing a variable twice without an intervening sequence point is one example of undefined behaviour.
the "a++ + ++a" expression causes an undefined behavior, as "a" is modified twice within a single sequence point (the "*" operator not constituting a sequence point). // same for the expression "++a * a++"
GCC → https://godbolt.org/z/vTGGc7PaM
CLANG → https://godbolt.org/z/hjKhjbWPn
sequence points → https://en.wikipedia.org/wiki/Sequence_point
0
the answer is 4. when the plus signs are in front of the variable things are done on the spot if after the variable ...addition is happening on the next line...so
third line is like:
b=a; a=a + 1;
4
0
I don't have a clue what Blackstorm was meaning, however as said it's operator precedence. Working from left-to-right.
You can visualize it better if you chuck in some parenthesis:
int a = 2;
int b = (a++) * (++a);