views:

134

answers:

1

The output of the following code is "321" without quotes. Why not "123"?

#include <iostream>
using namespace std;

int& inc(int& start)
{
 return ++start;
}

int main()
{
 int i = 0; 
 cout << inc(i) << inc(i) << inc(i) << endl;
}
+6  A: 

Your code invokes Unspecified Behaviour because the order of evaluation of the arguments of operator<< is unspecified

Calls to operator<< modify the same variable. Don't write such code.

Note : Note that the code doesn't result in undefined behavior because there are sequence points (at least one function call) between when i is modified and when it is read'.

Prasoon Saurav
So does it or doesn't it invoke undefined behavior? :)
Eli Bendersky
Undefined, no. Unspecified, yes. More reading here (http://www.devx.com/tips/Tip/12684)
Alex Emelianov
@Eli : Function call is indeed a sequence point (note `operator<<` is an overloaded function), so it doesn't invoke Undefined Behavior.
Prasoon Saurav
@Alex : IMHO the article by Danny Kalev is flawed. Unspecified Behaviour doesn't guarantee same output (behavior) between different runs. Also read [this](http://stackoverflow.com/questions/3296523/is-implementation-defined-behavior-required-to-be-consistent-between-runs-in-c/) thread.
Prasoon Saurav
@Prasoon Saurav - The article isn't flawed, but out of date. See the date "September 4, 1998" on the article. I believe a lot has changed in C++ after that.A guy involved with the standardization process of C++ wouldn't be dishing out crap !!
DumbCoder
@DumbCoder : Hmm but I have also seen him calling `<iostream.h>` a deprecated header but it is not. I never said that the article was crap. One should not give reference to such an old article.
Prasoon Saurav
@Prasoon Saurav - I believe you are again referring to old articles of Danny(http://www.devx.com/tips/Tip/14447), while you yourself mention not referring to old articles ?
DumbCoder
@DumbCoder : My only point is that `<iostream.h>` should not be called deprecated because it was never a part of the Standard. Danny Kalev incorrectly calls it a deprecated header. This article was written after the release of C++98.
Prasoon Saurav
@Prasoon Saurav - If I am correct the first standard was ratified in 1998, 19 years after it was written. Till 2002 most compilers supported both <iostream> and <iostream.h>. So it mayn't be totally wrong to call <iostream.h> deprecated. If you intend to intrepret the standards so strictly, then probably boost wouldn't have ever become a part of the new C++ standards.
DumbCoder
@DumbCoder: and it hasn't (boost become part of the new standard). Only some libraries have affected the standard by providing a use case and sample implementation, but the standard has reworked most (if not all) of them, sometimes only in the underlying implementation, sometimes in the interface or the semantics.
David Rodríguez - dribeas