cout not printing variables as they truly are or inhibiting update of memory...

I've never experienced this before in all my time programming c++.
But this is just so wtf just look...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace 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.
operator<< is a right to left operator.

http://en.cppreference.com/w/cpp/language/operator_precedence

The output you get looks correct to me if evaluated right to left.

I'm not sure having functions that make modifications to variables in print statements is a terribly good idea though.
Operator precedence doesn't come into play here.

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!
Topic archived. No new replies allowed.