about output of pointer of functions: output sequence

my question is that why the output sequence like that? see the output plz following.

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
int hi(int);
int hie(int);
int hiee(int);

int main()
{
	int (*(ph[3]))(int) = {hi, hie, hiee};
	cout << (**ph)(0) << endl << (*(ph[0]))(2);

	cin.get();
}
int hi(int xx)
{
	cout << "HI" << endl;
	return 100;
}

int hie(int)
{
	return 1;
}

int hiee(int)
{
	return 10;
}


output:
HI
HI
100
100

why print two HI first then 100?

Doesn't it should be
HI
100
HI
100
Actually it can be both: it is example of undefined behavior. What happens is that program calculates values of all operand before executing even one operator<< which it can do by standard: order of operand values calculations is not guaranteed — you could look at you program like that:
operator<<( operator<<( operator<<( cout, (**ph)(0) ) , endl) , (*(ph[0]))(2) )
And AFAIR gcc will calculate operand values right to left...

Edit: Another example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int foo()
{
	std::cout << "foo" << std::endl;
	return 100;
}

int bar()
{
	std::cout << "bar" << std::endl;
	return 1;
}

int main()
{
	std::cout << foo() << std::endl << bar();
}
Outrut:
bar
foo
100
1

what probably happens:
bar() executed, 1 pushed to stack
foo() executed, 100 pushed to stack
&cout pushed in fron of stack, operator<< called with operands equals to last tvo values on stack: that is &cout (where we will output to) and 100 (What we will output).
It pops these two values from stack and pushes result: &cout again.
Operator<< called again, now his arguments are &cout (Was placed by result of previous call) and 1 (was here already)...
Last edited on
@MiiNiPaa

I now get the point~ Thanks a lot! :D
To be more precise, this is not undefined behavior (anything can happen, can be optimized out, can crash, etc), this is unspecified behavior: the program is well-defined, only one of the two possibilities will happen, and which one depends on the compiler.

Quick compiler shoot-out:

clang-3.2, intel-13.1, Sun Studio 5.10, IBM XLC 11.1, gcc-4.7.2 on AIX
HI
100
HI
100


gcc-4.7.2 on Linux
HI
HI
100
100
With function, which takes 3 arguments there will be 6 possibilities. And so on. But that's it: it is unspecified behavior — order of function argument calculation is not specified and can change (i.e. for optimization).
Topic archived. No new replies allowed.