3 ms·
In response to the last paragraph, there's a tension between two different visions for the C language. One of the visions is what's sometimes called "high-level
by jacquesgt 14y ago
In response to the last paragraph, there's a tension between two different visions for the C language. One of the visions is what's sometimes called "high-level assembly language". In that case, undefined behavior lets implementors choose the behavior that makes the most sense in that situation. Someone writing software for a DSP is going to have different expectations for the behavior or integers than someone writing software for a general purpose processor. Forcing both implementations to use the exact same semantics is going to slow both of them down, because extra checks will have to be added to work around the differences in the underlying hardware.
The other vision for C is a portable systems programming language. When trying to write portable code, undefined or implementation-defined behavior is a big problem. I'm glad that compiler writers employ a take-no-prisoners approach here. People shouldn't be relying on undefined behavior when trying to write portable code, so compiler writers shouldn't be bound to implement consistent behavior in those cases. That's especially the case if code ever needs to be compiled with a different compiler, which might decide to implement different consistent behavior.
It's also worth noting that in some cases, the exploitation of undefined behavior doesn't always happen in a single place in a compiler. Instead, it can be a combination of applying a few different rules in different optimization passes that produces surprising results.
With that being said, it sure would be nice if the compiler writers figured out how to give more warnings when undefined behavior is detected. If x + 1 > x is optimized to false, tell me! If a dereference of a pointer that could be null leads to potentially dead code being eliminated, tell me about that too! It's the silently surprising behavior that causes the most problems.
- cliffbean 14y agoVirtually all CPUs today implement two's complement signed integers natively. Even the few C-capable DSPs that I know about do too (and have separate types and operations for saturation etc.). The main loss would be the compiler optimizations, and most of those can be recovered if programmers can avoid a few pitfalls, such as the ones I discussed. The problem with undefined behavior is not people ignoring portability. It's that it's actually really easy to accidentally misuse it. For example, Regehr's group has found quite a few such bugs in widely ported code written by smart people [0]. [0] http://embed.cs.utah.edu/ioc/ http://embed.cs.utah.edu/ioc/