3 ms·
> I have presented Undefined Behavior as a tool that enables the programmer to write code that the compiler cannot check for correctness, and argued that — used
by kazinator 4y ago
> I have presented Undefined Behavior as a tool that enables the programmer to write code that the compiler cannot check for correctness, and argued that — used responsibly — it is a useful component in a language designer's toolbox.
That is simply wrong. Code that the compiler cannot or does not check for correctness isn't "undefined behavior". Traditionally that is called "unsafe code": the programmer ensures safety through analyzing all the cases that may occur and making sure they have reliable consequences.
(The article talks about Rust a lot; maybe undefined and unsafe are the same thing in Rust?)
Undefined behavior with ill consequence may co-occur with safety. A case of undefined behavior may be flagged by the compiler by a diagnostic "undefined behavior in line 42". Thus, safety was ensured; the situation was diagnosed. Yet, an executable program could be produced anyway, and if that is run, it may mishbehave due to that undefined behavior in line 42.
This is the case in C, when you assign incompatible types, and use a compiler like GCC which only warns about that, by default, and translates anyway.
Some undefined behavior leads to a documented extension, which makes it defined for the given implementation, and safe (if used as documented). If you try to perform arithmetic on a void * pointer, that is not an ISO C feature; it requires a diagnostic. GCC allows void * pointer arithmetic; it behaves like byte addressing. Programs which use this feature are invoking undefined behavior: they are violating an ISO C constraint rule, yet being executed anyway. Furthermore, if the diagnostic isn't issued, then GCC is being a non-conforming implementation; it's a non-conforming extension.