c++language-lawyerevaluation

is "Side effects of a function are sequenced before its evaluation" specified by the C++ standard?


I didn't find relevant terms in Order of evaluation.

So is the behavior of function g undefined in the code below?

int x;
int f() { return x++; }
void g() { x = f(); }

I compiled the code on different platform and with different args, and it showed that x always stayed unchanged.


Solution

  • is the behavior of function g undefined in the code below?

    No.

    is "Side effects of a function are sequenced before its evaluation" specified by the C++ standard?

    Yes.

    I mean, from a logical point of view, a function has to "end" before anything else can start.

    Before C++11 and in C, we have "sequence points". Each full expression ends with a sequence point. At the end of full expression return x++ at ; all side effects have to be evaluated.

    After C++17 we have this from https://timsong-cpp.github.io/cppwp/n4659/intro.execution#18 :

    For each function invocation F, for every evaluation A that occurs within F and every evaluation B that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any), either A is sequenced before B or B is sequenced before A

    f() has to be value evaluated before assignment to x in x = f(). So all evaluations inside f() have to happen before assignment to x. Including any side effects from return x++;.