Remix.run Logo
▲ _kst_ 5 hours ago

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.

▲eru 4 hours ago | parent | next [-]

> 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.

Compilers warn about perfectly well defined behaviour all the time. That's why these are warnings, not errors.

▲afdbcreid 4 hours ago | parent | prev [-]

You can perfectly specify that integer overflow either traps or wraps-around (this is what Rust does). Then the flag would be conforming. You can also say it is Erroneous Behavior (a new term in C++, not yet adopted for C AFAIK) and specified to wrap-around, which will also allow the flag (and arguably models Rust behavior more closely).