Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the evaluation of a function call's "this" in an unspecified order relative to the parameters?

It's widely-known (though not widely enough >.<) that C and C++ don't specify the order in which parameters to a function are evaluated. That is, the two puts()s below can occur in either order, as an arbitrary compiler choice:

#include <cstdio>

int Function1() {
    std::puts("Function1");
    return 1;
}

int Function2() {
    std::puts("Function2");
    return 2;
}

int Add(int x, int y) {
    return x + y;
}

int main() {
    return Add(Function1(), Function2());
}

However, does this also apply to the evaluation of this on the left side of the ., .*, -> or ->* operators? In other words, is the order of the puts()'s below also unspecified?

#include <cstdio>

struct Struct {
    Struct() { std::puts("Struct::Struct"); }
    int Member(int x) const { return x * 2; }
};

int Function() {
    std::puts("Function");
    return 14;
}

int main() {
    return Struct().Member(Function());
}
like image 551
Myria Avatar asked Jul 24 '15 23:07

Myria


1 Answers

Struct().Member(Function())

This is a function call where the postfix-expression is Struct().Member and the argument is Function(). In general, in a function call, the evaluation of the postfix-expression is unsequenced with respect to the evaluation of arguments.

Therefore the order of the puts calls is indeed unspecified.

It's completely irrelevant that the function is a non-static member function.

like image 113
Brian Bi Avatar answered Nov 14 '22 21:11

Brian Bi