#include <iostream>
usingnamespace std;
class obj {
public:
int val;
string print() {
val=55;
return"str";
}
};
int change(int& pass) {
pass=34;
return pass;
}
int main() {
int var=55;
obj tst;
tst.val=100;
cout<<var<<change(var)<<var<<endl;
cout<<tst.val<<tst.print()<<tst.val<<endl;
cout<<var<<" "<<tst.val<<"--normal now"<<endl;
return 0;
}
the output of this program with g++ is like so...
1 2 3
343455
55str100
34 55--normal now
Yes this is only happening when I call functions through the << operator with cout (or at least I haven't tried all the different ways to get this sort of thing to happen). I know the workaround to avoid this but my question is WHY?
I wouldn't be posting this here if I hadn't found nothing on this at all anywhere. This is just hard to believe for me to be normal (desirable?) behaviour.
The standard doesn't impose any order on the evaluation of var, change(var) and var on line 22, likewise line 23, so those expressions may be evaluated in any order. The only thing the standard requires here is that each expression is sequenced before the function it's an argument to (the overloaded operator<<) is called.
Just one click from that link about operator precedence is the page that explains order of evaluation in C++: http://en.cppreference.com/w/cpp/language/eval_order which even uses cout << i << i++ as an example of undefined behavior.
ok, good to know. I typically don't modify variables as I print them which is why I've never seen this. I was just worried at least the function in a cout does get called and do real things to memory I was just surprised that the order was not left to right as cout<<a<<b<<c typically prints left to right in my experience I never in a million years anticipated this. Thanks a bunch for the clarity guys!