Re: Evaluation order
On 12.09.2013 10:46, Stefan Ram wrote:
#include <iostream> /* ::std::cout */
#include <ostream> /* << */
#include <cstdio> /* ::std::putchar */
int main()
{ ::std::cout << ::std::putchar( 65 )<< ::std::putchar( 66 )<< '\n'; }
When using an ASCII execution character set, the above
can print
AB6566
or
BA6566
, but could it also be possible that it prints
A65B66
?
Your expression evaluates to
cout.operator<<(putchar(65)).operator<<(putchar(66)).operator<<('\n')
including this pointers it looks like
operator<<(operator<<(operator<<(cout, putchar(65)), putchar(66)), '\n')
defining an evaluation tree
a = putchar(65)
|
b = operator<<(cout, a) c = putchar(66)
| |
d = operator<<(b, c) --------------+
|
operator<<(d, '\n')
The calls to putchar(65) and putchar(66) have no defined sequence.
But all calls to operator<< are in order.
Unfortunately putchar does not output to cout. It uses stdout. Both,
cout and stdout are allowed to use their own buffers. So although the
function calls have a defined order the output of operator<< and putchar
is not synchronized in any way. You might even see
6566
AB
Since most iostream implementations simply wrap to the stdio API
(everything else could be too fast, I guess) it is not very likely that
the output from cout precedes the direct output over the stdio API.
Marcel