Monday, March 1, 2010

float comparison and POD equality

I found an interesting discussion on why there is no default comparison operator (operator==) on PODs even though there is a default assignment (operator=). 

operator= can be trivial for PODs as byte=by-byte copy will produce an equivalent result to an element by element copy. Essentially memcpy will work as operator= for PODs. At first you might think that operator== could work the same way, lets just use memcmp.

However theres a spanner in the works - floats cause us some problems. And not in the usual "floating point comparison for numbers that are very close together not showing up as equal" - but something a little more subtle. 

For most floats the bit patterns being equal means the floats are equal and vice versa. However theres a couple of exceptions. -0.0 == 0.0 even though the bit patterns are different. Also NaN != NaN even though the bit patterns are the same.

This means that a bit by bit POD operator== can never work the same way as an element by elememt comparison when floats (or doubles) are in the mix. And that means no default operator==. A sad loss, but maybe a little more understandable to me now.