Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ! ( x < y ) and x >= y in C++?

Going through EASTL, I stumbled across a peculiar line of code. The following link shows the file with the line number of interest at 1870.

https://github.com/paulhodge/EASTL/blob/master/include/EASTL/algorithm.h

The code at that line is if(!(value < *i)). The comment says that "we always express value comparisons in terms of < or ==" without any explanation as to why this is so. There are also a few other areas where the same comment is placed but without any explanation.

Is there any benefit whatsoever to writing a comparison like that (maybe some context that I am overlooking)? If not, why did the author of EASTL deliberately wrote it in this particular fashion and even took the care to comment about it? Is consistency the only reason here?

like image 827
Samaursa Avatar asked Jan 05 '12 03:01

Samaursa


2 Answers

It means you only need to provide < and == for container value types. It also means you reduce the amount of variability for those types (as all the algorithms use !(a<b) to mean a>=b and !(a==b) for a!=b); otherwise, you could have >= and != return inconsistent results.

like image 75
MSN Avatar answered Nov 02 '22 23:11

MSN


In C++, you can overload the < operator so that it behaves differently than the opposite of >=, so they are not guaranteed to be equivalent.

Additionally, in any IEEE floating-point implementation, NaN < NaN is false, but so is NaN >= NaN, so !(NaN < NaN) is true even though NaN >= NaN is false.

like image 26
Gabe Avatar answered Nov 03 '22 01:11

Gabe