▲ | OskarS 4 days ago | |||||||||||||||||||
No, it's absolutely because of optimization. For instance, C++20 defined signed integer representation as having two's complement, but signed integer overflow is still undefined behaviour. The reason is that if you compile with flags that make it defined, you lose a few percentage points of performance (primarily from preventing loop unrolling and auto-vectorization). Same thing with e.g. strict aliasing or the various UB that exists in the standard library. For instance, it's UB to pass a null pointer to strlen. Of course, you can make that perfectly defined by adding an `if` to strlen that just returns 0. But then you're adding a branch to every strlen, and C is simply not willing to do that for performance reasons, so they say "this is UB" instead. Pretty much instance of UB in standard C or C++ is because making it defined would either hamper the optimizer, or it would make standard library functions slower. They don't just make things UB for fun. | ||||||||||||||||||||
▲ | pizlonator 4 days ago | parent | next [-] | |||||||||||||||||||
This isn’t the reason why the UB is in the spec in the first place. The spec left stuff undefined to begin with because of lack of consensus over what it should do. For example the reason why 2s complement took so long is because of some machine that ran C that still existed that was 1s complement. > The reason is that if you compile with flags that make it defined, you lose a few percentage points of performance (primarily from preventing loop unrolling and auto-vectorization). I certainly don’t lose any perf on any workload of mine if I set -fwrapv If your claim is that implementers use optimization as the excuse for wanting UB, then I can agree with that. I don’t agree that it’s a valid argument though. The performance wins from UB are unconvincing, except maybe on BS benchmarks that C compilers overtune for marketing reasons. | ||||||||||||||||||||
| ||||||||||||||||||||
▲ | account42 4 days ago | parent | prev [-] | |||||||||||||||||||
I wish there was a way to opt into undefined behavior for unsigned overflow. Its rare that wraparound is actually what you want and in many cases overflow is still a bug. Sucks to have to either miss out on potential optimizations or miss out on the guarantee that the value can't be negative. | ||||||||||||||||||||
|