I am trying to implement a comparator function, and coming from a JavaScript background attempted to chain them like so:
int MyClass::compare(MyClass & other) {
return MyClass.x.compare(other.x) || MyClass.y.compare(other.y);
}
That is, compare the objects' x
values, and if they are equal compare the objects' y
values.
I immediately realized this wouldn't work, because the OR function in c++ returns a bool rather than the last evaluated value.
Other than literally writing an if statement, like
int result = MyClass.x.compare(other.x);
if (result) {
return result;
}
result = MyClass.y.compare(other.y);
return result;
, is there is a concise way to write this expression?
(condition) ? ture_case : false_case
syntax? this can be nested (but better use parenthesis). – user9400869 Dec 6 '19 at 6:09compare
returning a value? It doesn't make sense with that name. It should returns -1, 0 or 1 like the spaceship operator. Or use.equals()
and return a bool – phuclv Dec 6 '19 at 6:12return (result = my.x.compare(other.x)) ? result : (result = my.y.compare(other.y))
which IMO becomes unreadable after a while and is pretty much the same as the if statement method. – Moshi Dec 6 '19 at 6:15||
operator in js is just such a thing, in many cases, it seems to be clear for what it is used, e.g. to define a default value. But using it for a default value does not work for every case, so you always need to think about if it is valid to use it in that case, and in a code review you will always need to double-check if the||
is valid. And as you can't use||
in every case then those where you don't use||
might look wrong/off. – t.niese Dec 6 '19 at 10:07