Taking an intro c++ class, and the professor today was talking about loops, increments, and decrements. so we were examining how many times a simple do-while loop would run, and I noticed that during the output of the following code, the int y is displayed first as a 2, however the postfix-notation for increments is used first and, according to my professor, is also given precedence(like in the x variable displayed). so why is y not first displayed as: "1 3" in the output window?
probably a very simple answer, but he did not know immediately, and asked us to see if we can find out. we were using dev c++'s newest version.
#include <iostream> using namespace std; int main() { int x=1; int y=1; do { cout << "x: " << " " << ++x << " " << x++ << endl; cout << "y: " << " " << y++ << " " << ++y << endl; }while(x<=10); return 0; } if you run it, the display will look like this:
x: 3 1 y: 2 3 x: 5 3 y: 4 5 x: 7 5 y: 6 7 x: 9 7 y: 8 9 x: 11 9 y: 10 11 with my limited understanding i came up with this: since there are multiple increment operations used in the same statement, they are both performed before the cout statement displays the information to the console.
but looking for maybe a more precise answer/explanation
Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. Unlike a function call, the << and >> operator does not create a sequence point.