2

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

12
  • 2
    stackoverflow.com/questions/5433852/… Commented Mar 1, 2013 at 2:58
  • 3
    it seems to be a undefined (or implementation-dependent) behavior for C++, with multiple assignment to the same variable in same statement. Commented Mar 1, 2013 at 3:01
  • 1
    @Dave: the issue is that the standard specifies: 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. Commented Mar 1, 2013 at 3:41
  • 1
    @Dave: however the << and >> here is an overloaded operator, and overloaded operator does introduce sequence point like function calls. I'm not actually quite sure whether this should be an undefined behaviour. Commented Mar 1, 2013 at 3:51
  • 1
    @LieRyan Why do you think overloaded operators introduce extra sequencing? Commented Mar 1, 2013 at 3:51

1 Answer 1

1

++y increments and assigns the new value of y before a reference of int y is passed to operator<<(std::ostream&, const int&) and y++ increments and assigns y after operator<<(std::ostream&,const int&) returns

So, you land up printing 2 the first time because y=1 is passed in to opertator<< y++ is called to print 2, and after the call to operator<< y is assigned 2.

The second call to operator<< on y has y set to 2, ++y is called before the reference is passed to operator<< and y is 3.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.