4

I have this snippet of code in c++:

std::vector<int> v1;
std::vector<int> v2;
...
if (v1.insert(v1.end(), v2.begin(), v2.end()) == v1.end())
{
    return 0;
}

Which expression will be evaluated first? When debugging, the right side of "==" operator is evaluated first, is this the right behaviour?

user3691223
  • 353
  • 2
  • 11

2 Answers2

12

This has nothing to do with associativity (that comes into play in expressions like a == b == c). What you're asking about is the order of evaluation of an operator's operands. With a few explicitly listed exceptions, this is intentionally unspecified in C++. This means there is no guarantee whether a or b will be evaluated first in a == b.

The exceptions (for which evaluation order is guaranteed), are:

  • All arguments to a function call are evaluated before the function call itself (but in an unspecified order).
  • The left-hand side of the built-in operators || and && is evaluated first (and the right-hand side is only evaluated if necessary).
  • The left-hand side of the built-in operator , is evaluated before the right-hand side.
  • The condition in operator ?: is evaluated before the consequent, and only one of the consequents is evaluated.

Notice that the special properties of &&, ||, and , cease to apply when these operators are overloaded. This is precisely the reason why it's a bad idea to overload these three operators.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
4

You are not asking for the associativity of operator ==, but about the order of evaluation. And the order of evaluation is unspecified for this operator, so you have to assume that the order is always that which does not work for you. Split your statement in two lines to be safe.

Kijewski
  • 25,517
  • 12
  • 101
  • 143