Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associativity of == operator in c++

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?

like image 526
user3691223 Avatar asked Dec 03 '22 22:12

user3691223


1 Answers

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.

like image 145
Angew is no longer proud of SO Avatar answered Dec 24 '22 09:12

Angew is no longer proud of SO