Re: [Dev-C++] Problem with 'std::cout' (?)
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: matheus r. <mfr...@gm...> - 2007-10-05 16:37:06
|
Elaborating a bit more on the problem. The C/C++ compiler is free to
evaluate function parameters in any order. In the case of gcc/g++,
function parameter evaluation happens from right to left. Also, all
parameters have to be evaluated before function call.
The function:
--- ostream &operator <<(ostream &, int)
acts just like:
--- ostream& write(ostream &s, int i){ s.write(i); return s; }
Thus, this statement:
--- cout << f1() << f2() << f3();
is equivalent to:
--- write3( write2( write1(cout, f1() ), f2() ), f3() );
because the << operator is evaluated from left to right. I renamed
functions to make it easier to explain (write1, write2, write3 are the
same, like f1, f2 and f3).
When compiler sees this, it:
1- evaluates write3 right parameter, f3r = f3().
2- evaluates write3 left parameter, write2( write1(cout, f1() ), f2() ).
2.1 - evaluates write2 right parameter, f2r = f2()
2.2- evaluates write2 left parameter write1(cout, f1() )
2.2.1- evaluates write1 right parameter, f1r = f1()
2.2.2- call w1r = write1(cout, f1r)
2.3- call w2r = write2(w1r, f2r)
3- call write3(w2r, f3r)
So, the f functions will be called in the order: f3(), f2(), f1()
before any of the write functions due to parameter order evaluation.
The write functions will happen in the order write1(), write2(),
write3().
As a result, the f functions will be called in reverse order, but the
stream will be written in correct the order. The side effect of the f
functions are responsible for the weird result you see. If a function
has a side effect on itselft, you can not rely on the order of
parameters if its called multiple times as parameters, since each
compiler is free to evaluate parameters in any order.
Sorry for bringing this up again, just wanted to clear it up.
|