News for hackers. Stuff that matters.
Re:Modern C (2019) by bsder on Friday June 02, 2023 @03:48PM (#36169938)
No. The mistake is conflating "undefined behavior" with "unspecified behavior".

Signed overflow was not intended to be undefined--it was unspecified because it has a perfectly acceptable specification that differs between processors, and it was expected that the compiler would define it. The fact that gcc and clang pick non-sensical specifications in order to gain 3% in performance was not something anybody expected back when this stuff was written.

"Division by zero" is, on the other hand, genuinely undefined behavior. "Dereferencing a NULL pointer" is a genuinely undefined behavior. There generally isn't a good way for a program to continue after encountering them.

Re:Modern C (2019) by aw1621107 on Friday June 02, 2023 @04:33PM (#36170379)
> Signed overflow was not intended to be undefined--it was unspecified

This seems wrong to me. The Standard very much calls signed overflow undefined behavior (Section 3.3):

> If an exception occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not representable), the behavior is undefined.

In addition, overflow is explicitly listed as undefined behavior in at least two other places. For example, in section 1.6, Definitions of Terms:

> An example of undefined behavior is the behavior on integer overflow.

And in the list of undefined behavior (A.6.2):

> An arithmetic operation is invalid (such as division or modulus by 0) or produces a result that cannot be represented in the space provided (such as overflow or underflow) (3.3).

If signed overflow was not intended to be undefined, then it seems like a rather large oversight to say it's undefined behavior and to give it as an example of such.

> because it has a perfectly acceptable specification that differs between processors, and it was expected that the compiler would define it.

What you're describing is implementation-defined behavior in the C standard. If it was expected that implementations would define the behavior, why didn't the committee just... use that definition, instead of saying signed overflow is UB but actually meaning it's implementation-defined behavior?

In addition, unspecified behavior is a third category of behavior distinct from undefined and implementation-defined behavior. The Standard imposes no requirements on unspecified behavior in a correct program, and does not require that an implementation document what it does in such a situation.

[0]: https://port70.net/~nsz/c/c89/c89-draft.html