3 ms·
bool foo(int x) { return x+1 > x; } This compiles to a function that always returns true on most compilers with optimizations turned on. If the value o
by leni536 5y ago
bool foo(int x) {
return x+1 > x;
}
This compiles to a function that always returns true on most compilers with optimizations turned on. If the value of `x+1` were merely implementation defined for `x == INT_MAX`, then it would still need to return false then, as it can't be larger than `INT_MAX`. Yet it returns true.
https://godbolt.org/z/hn3de1h49 https://godbolt.org/z/hn3de1h49
edit: correction, clang and gcc optimize this to always true, MSVC doesn't.
- skissane 5y agoThat’s still “static” in the sense that it is only dependent on compilation options and data types, not the actual value of those data types at runtime. There is nothing there which could not trivially be determined by executing a test program-which is what the comment to which I was originally replying was talking about. Imagine if there was a ‘set_thread_signed_overflow_behavior()’ API which dynamically set signed overflow behaviour at runtime. That would be an example of undefined behaviour which could not be easily detected by executing a test. But, although such an API is permitted by the standard, I’ve never heard of one actually being implemented-well, it exists for floating point (fesetexceptflag FE_OVERFLOW), but (to my knowledge) no mainstream platform has an equivalent for integers. It can be a reasonable engineering decision to ignore those (exceedingly?) rare platforms on which such an API exists for integers, and save thinking about them for the unlikely event you are asked to port to one of them - which will probably never happen, especially not any time soon.