Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator== order in C++

Is there ever any difference when it comes to order with the operator==?

I came across an old exam where it says:

observe that *it1 == *it2 is not the same as *it2 == *it1

it1 in this case is an iterator of some type IT1 and it2 is an iterator of some type IT2. IT1 it1 and IT2 it2 are taken as parameters to a function, where IT1 could be the same as IT2. Example code:

template <typename IT1, typename IT2>
bool f(IT1 it1, IT2 it2) {
    return *it1 == *it2;
}

Any thoughts? In my head, order should not affect the outcome of operator==, so I'm confused.

like image 961
Myone Avatar asked Jan 31 '26 12:01

Myone


1 Answers

Yes, there can be a difference, because a given implementation of operator== can be asymmetric. Generally speaking this is not a very good way to code, but it can happen. == is symmetric for primitive types like int, but for user-defined classes anything can happen.

like image 163
Tom Tromey Avatar answered Feb 03 '26 03:02

Tom Tromey