0
What's the difference between these blocks of code? (with ++i increment)
// example 1 int a = 3; int b = ++a; // a is now 4, thus b is 4 int c = ++a; // a is now 5, thus c is 5 int d = b + c; // 4 + 5 cout << d << endl; // the result is 9 // example 2 int e = 3; int f = (++e) + (++e); // ??? cout << f; // result is 10 (profit?) As I understand it, ++i means increment the value of i then returns the incremented value, as opposed to i++ which returns the value before operation. Explanation?
3 Respostas
0
Code Playground:
http://www.sololearn.com/app/sololearn/playground/c7BLm0LMpnvi/
0
That is because of the Operator Precedence in C++. It executes the postfix and prefix operation always before the addition/subtraction operation.
http://en.cppreference.com/w/cpp/language/operator_precedence
0
Hi. I understand that the postfix and prefix is executed before the addition, but where does the extra 1 coming from? Since they were executed before the addition, wouldn't that leaves 4 and 5 to be added? Care for step by step explanation on what happened during f = (++e) + (++e)?