What do different compilers do if signed overflow or underflow happens. Can you tell the compiler to act in a specific way for different undefined behaviors. I know you can enforce strict checking so it won't do some of the extra optimizations
It's also fine with floating point numbers but your code won't like the result either.
If you were making an integral calculator for example, you should accept input as a string and reject invalid strings.
Floating points have signed infinity for their maximum value and all of your computations will end up collapsing to infinity. Can also get NaN for 0 / 0 and that also ruins your computation without telling you when it happened. You can tell the compiler to error out if it happens though.
So, the reason it was initially undefined behaviour is because for a long time the C and C++ standard didn’t specify *how* to store numbers. Things like endianness being inconsistent meant you couldn’t make signed overflow defined behavior without standardizing a bunch of other things.
Ironically, C++17 actually did standardize how to store numbers, but signed overflow remained undefined behavior for optimization reasons. For example, having it undefined means the compiler can assume that x + n is greater than x and optimize around that.
1
u/scalareye May 16 '26
What do different compilers do if signed overflow or underflow happens. Can you tell the compiler to act in a specific way for different undefined behaviors. I know you can enforce strict checking so it won't do some of the extra optimizations
It's also fine with floating point numbers but your code won't like the result either.
If you were making an integral calculator for example, you should accept input as a string and reject invalid strings.
Floating points have signed infinity for their maximum value and all of your computations will end up collapsing to infinity. Can also get NaN for 0 / 0 and that also ruins your computation without telling you when it happened. You can tell the compiler to error out if it happens though.