1

Consider a class Foo of which foo is an instance.

Foo has a function calculate() that changes an internal member for which watermark() is the "getter", and returns something with the same type as that internal member.

Is the expression

foo.calculate() != foo.watermark()

well-defined. That is, must calculate() happen before watermark() is called?

In order words, is the evaluation order strictly foo.calculate(), followed by foo.watermark() followed by !=?

  • 3
    There are no sequential point between both, the order of evaluation is unspecified. – Jarod42 Jul 18 '17 at 10:02
  • clear duplicate of [Undefined behavior and sequence points](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – underscore_d Jul 18 '17 at 10:09

3 Answers3

4

There are no sequential point between both, the order of evaluation is unspecified.

You have to force sequence as for example:

const auto& res = foo.calculate();
res != foo.watermark();
Jarod42
  • 203,559
  • 14
  • 181
  • 302
3

The C++ Standard(ISO/IEC 14882:2014) say's :

Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread, which induces a partial order among those evaluations. Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. If A is not sequenced before B and B is not sequenced before A, then A and B are unsequenced. Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which.

Do not allow the same scalar object to appear in side effects or value computations in both halves of an unsequenced or indeterminately sequenced operation.

Reference link here.

msc
  • 33,420
  • 29
  • 119
  • 214
0

It may help: http://en.cppreference.com/w/cpp/language/eval_order

Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified. The compiler can evaluate operands in any order, and may choose another order when the same expression is evaluated again.

Zefick
  • 2,014
  • 15
  • 19