10 ms·
The undefined behavior is there so that the language can be used across heterogeneous systems. 9-bit chars, 36-bit words, 1's complement arithmetic, decimal reg
by kevin_thibedeau 11y ago
The undefined behavior is there so that the language can be used across heterogeneous systems. 9-bit chars, 36-bit words, 1's complement arithmetic, decimal registers, NULL somewhere other than address 0? You can have all that with standard compliant C.
- marvy 11y agoFine, so keep those aspects. There still remains plenty of relatively pointless undefined behavior. For instance, is the following well defined? int f(int* p, int* q){return ++p + ++q;} It depends! It depends on whether p == q. If so, it is not defined, and on high optimization levels, compilers will tend to give the wrong answer, but on low levels not so much. I bet a lot of people (but probably not all) would be willing to take the speed hit so that this becomes well defined, as it is in most other languages. (Note: I haven't fact checked anything I wrote here; no doubt some language lawyer will correct me if I'm wrong.)
- kazinator 11y agoWe don't even have to take the speed hit. Why? Because here is how the unspecified evaluation order benefits the above scenario: the compiler doesn't have to reason about whether p == q. But since C99 we have had a tool by which we can tell the compiler, "trust me, p != q". Namely: int f(int * restrict p, int * restrict q) { ... } So with this, even if we have strict left to right order, it can still reorder the code the same as before.
- scott_s 11y agoOf your examples, I believe only dereferencing 0 is undefined behavior. The rest are, I believe, implementation defined. It is implementation defined behavior which allows C to be used across heterogenous systems. I talk about the difference elsewhere in this thread: https://news.ycombinator.com/item?id=10839389 https://news.ycombinator.com/item?id=10839389