Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the expression left() = right(), why is right() sequenced first?

In C++, the expression left() = right() evaluates

  1. right()
  2. left()

in that sequence. The right() goes first, as has been discussed here.

I cannot think of a reason for right() to go first. Can you? I presume that there exists a reason. Otherwise, the standard would hardly say what it says, but consider: right() will return some result. At the machine-code level, does the CPU not need to know where to put the result right() will return before asking right() to return it?

If you happen to know what the standard committee was thinking (because you were in the room or have read the memo), that's great: I'd like to read your answer. However, my actual question is more modest. All I want to know is whether there exists a plausible reason and what that reason might be.

like image 598
thb Avatar asked Mar 27 '19 21:03

thb


2 Answers

In addition to the unintuitive result when doing what Brian showed:

#include <map>
int main() {
    std::map<int, int> m;
    m[0] = m.size(); // before C++17 m[0] could be 0 or 1 - it was implementation defined
}

If we take a the same map but do:

#include <map>
int main() {
    std::map<int, int> m;
    m[0] = Right(); // Right() may throw
}

If Right() throws:

Before C++17 you could get a default constructed element in m[0] (left to right) or m[0] wouldn't be created at all (right to left). In C++17 m[0] will not get created at all.

like image 144
Ted Lyngmo Avatar answered Sep 21 '22 14:09

Ted Lyngmo


In the proposal P0145 that introduced this evaluation order, the authors gave the following example:

#include <map>
int main() {
    std::map<int, int> m;
    m[0] = m.size();
}

In this situation, left-to-right evaluation would give 1, whereas right-to-left evaluation would give 0. Having the result be 0, thanks to right-to-left evaluation, corresponds more closely to our intuition that the value that should be assigned is the one that existed immediately before the assignment expression was evaluated.

like image 43
Brian Bi Avatar answered Sep 19 '22 14:09

Brian Bi