0

While using cout if the statement is cout<<E1<<E2<<E3; then there is no guarantee that the E1 E2 and E3 will be executed in the same order they are written.

What can I do to make sure they execute in same order they are written without writing another cout statement or endl in between?

2 Answers2

0

I'm not sure if it's the best decision (or just a good one at least) but you can use Boost.Preprocessor:

#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>

#define COUT_IMPL(_, __, i) \
  std::cout << (i);
#define COUT(...) \
  BOOST_PP_SEQ_FOR_EACH( \
    COUT_IMPL, \
    _, \
    BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__) \
  );

void use() {
  COUT(e1, e2, e3);
} 

This makes C preprocessor create ;-terminated couts for you, providing guaranteed order of evaluation.

passing_through
  • 1,778
  • 12
  • 24
0

Unless your << operator is redefined, this will execute in the order written. The

cout << E1 

is executed first with a return type of std::ostream (unless of course we're playing games with a different cout type. cout is not a C++ keyword or reserved word). This side-effected cout is passed to the next expression:

cout << E2

The processing is repeated for the next argument. I'm not aware of any C++ changes to operator precedence. I can't think of any way to play with the C preprocessor or play with other really obscure overloading techniques where you might be able to do some atypical operations.

Richard Jessop
  • 897
  • 1
  • 12
  • 19
  • 1
    As far as I know, the stream operation execution order is well-defined but the evaluation order of those `E`s is not (until a certain language standard). – passing_through Apr 25 '20 at 06:34
  • If not well defined, then a type analysis on the return values from intermediate operations should result in a compiler error on at least one platform. Assuming R-L ordering, E2< – Richard Jessop Apr 25 '20 at 18:59
  • I'm afraid you misunderstood my point: the order of writing values to a stream is well-defined but the order of computing those values (if they are written as expressions like `cause_side_effect()`) is (was?) not. – passing_through Apr 25 '20 at 19:22
  • The light shineth. – Richard Jessop Apr 25 '20 at 21:08