3 ms·
Don't forget arithmetic operations that can detect various corner cases. Writing something like: sum = x + y; if(sum < x || sum < y) { ... } And
by aidenn0 7y ago
Don't forget arithmetic operations that can detect various corner cases.
Writing something like:
sum = x + y;
if(sum < x || sum < y) {
...
}
And then hoping the compiler will optimize your if statment to a single overflow CF check is a bit silly.
- jstimpfle 7y agoThat would not prevent the overflow from actually happening, which would be technically UB if the sum is a signed type. It is possible to catch overflow in the last instant like this (in the last instant before executing the addition instruction) but the test is more involved. It's a pity that there are no standardized tools (AFAIK) but it's not possible to write a substantial piece of code in this way, anyway. What you would generally do is assume that x and y can't be overflow. I.e. you need to have a rough idea what quantities you will process. And put a few checks and assertions in strategic locations.
- aidenn0 7y agoRight, I was assuming x and y were unsigned types at least as large as an integer. Tests for other types are different.
- comex 7y agoIf you just use `sum < x` or `sum < y` rather than both, C compilers do reliably perform that optimization. (You don't need both; `sum < x` and `sum < y` are always both false or both true.)