logoalt Hacker News

BeaverGoose • today at 3:03 AM • 4 replies • view on HN

Make signed overflow defined please.


Replies

_kst_ • today at 3:28 AM

I disagree, though I wouldn't mind adding a mechanism to say that you want signed overflow to be well defined.

C23 already requires 2's-complement representation for signed integer types, but signed overflow still has undefined behavior. I think that mandating 2's-complement wraparound would be a mistake.

Some instances of undefined behavior can be detected at compile time. For example, if I write

    int too_big = INT_MAX + 1;
a reasonably clever compiler can warn about it (and in fact both gcc and clang do so). If the result of INT_MAX + 1 were defined by the language to be INT_MIN, there would be no basis for such a warning.

If you evaluate n + 1 and it's possible for n to be equal to INT_MAX before the addition what do you want the result to be? Would quietly yielding INT_MIN really be useful?

Ideally, if I (accidentally) evaluate INT_MAX + 1, I'd like to be told that I've made a mistake. C doesn't have a good mechanism for doing so.

gcc has a non-standard option "-fsanitize=signed-integer-overflow" that can be used to catch signed overflow at runtime. If signed overflow yielded a well defined result, that option would be non-conforming.

➕ show 2 replies
creato • today at 3:55 AM

Why would this help? Unsigned integer overflow is defined behavior, that causes basically the same set of bugs in practice. In a way it is worse, because at least runtime UB checkers have a reason to complain about signed integer overflow, but they won't complain about unsigned integer overflow.

eru • today at 3:54 AM

It would be an improvement.

However if you wan, you can already get that via a flag in pretty much any C compiler you care about.

homosapien97 • today at 4:19 AM

Use -fwrapv

➕ show 1 reply