+ 2
#include<iostream> using namespace std; int main(){ int x=3; int y=2; x++; y*=x++ - ++y * ++x ;
why the answer is -42
3 Réponses
+ 21
x=3
y=2
x incremented by 1 //x=4 now
y *=4++ - ++2*++5
//y*=4 - 3*6
//y=2*(-14) //ie,-28
//for java
+ 7
Problem: The expression " y*=x++ - ++y * ++x ;" has undefined behavior. The result of running this program could be literally anything.
Reason: Common misconception that the expressions like "a + b + c" are evaluated from left to right, one operation at a time. This isn't true. It may be evaluated in any order or in parallel.
Most relevant info: http://en.cppreference.com/w/cpp/language/eval_order
How to avoid shooting yourself in the foot: Learn about undefined/unspecified behavior, sequence points and evaluation order. Don't change one variable more then once in one sequence point.
Some previous questions with relevant links:
https://www.sololearn.com/Discuss/1091728/?ref=app
https://www.sololearn.com/Discuss/989706/?ref=app
https://www.sololearn.com/Discuss/957040/?ref=app
https://www.sololearn.com/Discuss/1036434/?ref=app
https://www.sololearn.com/Discuss/1073271/?ref=app
https://code.sololearn.com/cBg3yJKuyCM9/?ref=app
https://www.sololearn.com/Discuss/957040/?ref=app
P.S. The title of the question should contain short description of what is the question about. The question contents should be placed in the question body. Relevant technologies should be placed in the tags, especially the language in question.
+ 3
The first thing which I would like to tell you is that you should not use multiple pre or post increment or decrement operators in a single statement on a single variable. It is discouraged as it leads to a lot of confusions and undefined behaviour.