Evaluation order

S

Stefan Ram

#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

?
 
M

Marcel Müller

#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
 
S

Stefan Ram

Marcel Müller said:
....
the
function calls have a defined order

I used to believe that the order of evaluation of the two
function calls ::std::putchar( 65 ) and ::std::putchar( 66 )
was implementation specified.
the output of operator<< and putchar
is not synchronized in any way

I understand your words to allow for the possibility that

A65B66

might be printed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

CIN Input #2 gets skipped, I don't understand why. 1
Crossword 2
How can I fix my pattern coding error in c++ 0
Cannot find my infinite loop 1
plus( 2, 3 ) 8
Character operations in C++ 2
Crossword 14
TF-IDF 1

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top