Remix.run Logo
Retr0id an hour ago

GCC -O1 and clang -O1 will both optimize this function under the assumption that inputs that cause signed integer overflow are never passed:

    int will_overflow(int a, int b) {
        int sum = a + b;
        if (b > 0 && sum < a)
            return 1;
        return 0;
    }
mbrock an hour ago | parent | next [-]

Right, good example, and both GCC and Clang offer well understood parameters for deciding, per compilation unit, what behavior you want for signed overflow (-fwrapv, -fno-strict-overflow, etc), so in reality it's quite far from spooky arbitrary nasal demons.

skydhash 20 minutes ago | parent | prev [-]

Wouldn’t be better to check both inputs before against the max value of that type instead of actually doing the overflow?

Retr0id 18 minutes ago | parent [-]

There are lots of better ways of doing this, but knowing why this one is bad/wrong requires the mental model described upthread.

(But also, what you describe would be incorrect, since two <MAX values can add to a value that is >MAX, and overflow)

skydhash 2 minutes ago | parent [-]

> But also, what you describe would be incorrect, since two <MAX values can add to a value that is >MAX, and overflow

I was maybe unclear. I meant, if you know a sum can introduce overflow (because you have a check right after), why not check the inputs before doing the sum, instead of checking the sum?