an interesting phenomenon about "cout", could anyone tell me why?

Let's see the code first.

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
28
29
30
31
32
33
34
35
36
37
struct box
{
	int a;
};
const int shishi(int *);
const box & hey(box &);

int main()
{
	int hello = 3;
	cout << shishi(&hello) << endl << hello << endl << endl;
	//output is 4 then 3

	box m = { 5 };
	cout <<hey(m).a << endl<<m.a<<endl;
	//output is 10 then 5

	cout << endl << endl << hello << endl << m.a;
	//output is 4 and 10,which means the in former 2 "cout"
	//they were not update in time. and later, here, they do.

	cout << endl << endl;
	int ll = 6;
	cout << ++ll << endl << ll;//while here the output update in time

	cin.get();
}
const int shishi(int * n)
{
	(*n)++;
	return *n;
}
const box & hey(box & aa)
{
	aa.a *= 2;
	return aa;
}



4
3

10
5


4
10

7
7

I wonder how cout works when encounter function calls.
Could anyone give me the answer plz, thank you in advance!
I wonder how cout works when encounter function calls.

The same way it works for any other expression. First, the expression is evaluated (according to operator precedence rules), and then the result is output.

So, in the case of a function, the function call is performed, and then the return value is output.
Last edited on
> cout << ++ll << endl << ll;//while here the output update in time

See: Undefined behavior in http://en.cppreference.com/w/cpp/language/eval_order
It's not about cout, it's about expression evaluation.

1. The order in which subexpressions are evaluated is unspecified (with some exceptions that do not apply here). Depending on compiler, optimization options, platform, etc, it can go either way, so, in

cout << shishi(&hello) << endl << hello << endl; // either 4 3 or 4 4
it's unspecified whether the second hello is read before shishi() is executed to modify it, or shishi() is executed first and then the second hello is read. I get 4 and then 4 on most (but not all) compilers available to me.

2. if a scalar is modified and read from without sequencing, the behavior is undefined:
cout << ++ll << endl << ll; // ERROR!
when the behavior is undefined, anything can happen: any output, crash, whatever. You have an error in your program.

see http://en.cppreference.com/w/cpp/language/eval_order for some details
Last edited on
Topic archived. No new replies allowed.