4 ms·
Imagine doing if(x) ..., where x can be NaN. Shouldn't that throw an exception in most cases? Why are our compilers not doing it that way?
by amelius 5y ago
Imagine doing if(x) ..., where x can be NaN. Shouldn't that throw an exception in most cases? Why are our compilers not doing it that way?
- xen0 5y agoShould it? It isn't obvious to me at all that throwing an exception in this case is the best behaviour. Throwing an exception when testing a value for 'truthiness' is extremely surprising. On the other hand, I would strongly discourage 'if(x)' where x is a float that may be NaN purely because the 'correct' behaviour here isn't clear to me.
- amelius 5y agoHow about the case where x is (y > 0)? If y is NaN, shouldn't x be boolean-NaN? And shouldn't if(x) throw an exception? Or shouldn't (y > 0) throw an exception if you don't want boolean-NaNs?
- xen0 5y agoThat's easy: y > 0 is False, not NaN. You may not think this is wise, but this is very much how comparisons with NaN are defined. And I think this is better than exception raising. Again, I think it would be _really_ weird for simple value comparisons to throw.
- amelius 5y ago> Again, I think it would be _really_ weird for simple value comparisons to throw. But ... why? You may say that NaN > 0 is defined as False, but we know that's not how programmers think, most of the time. In code like if(y > 0) steer_car_to_left() I don't want the compiler or the IEEE standard to make any choices for me! Let it throw, so emergency systems can kick in.
- ElevenLathe 5y agoThe compiler presumably can't know in most cases, but the runtime might be able to throw. It depends on the language implementation and the tradeoffs.