That said, I think defining things as implementation-defined is only really useful when you have specific feature-check macros you can use to determine the behavior.
Otherwise you are kind of just trading one type of portability for another: rather than relying on the way your compiler handles UB directly, you are relying on the way your compiler does some ID (implementation defined) behavior: if you run your code on a different compiler, or a different version of the current compiler, the ID could change completely and the unexpected result probably quickly leads to either UB or some functional bug anyways.
int add(int a, int b)
{
return a + b;
}
Do you want the compiler to reject this because (assuming it has external linkage) there's no guarantee that there is no call with arguments such that the addition would overflow?Overall though, this isn't how compilers work: they aren't "fucking around" with code they know for sure is broken and will be executed. They are just applying a large series of optimization passes which includes passes like removing unreachable code, and that interacts with an analysis of paths that cannot be take for various reasons (including that end in UB) to remove "big chunks of code".
The same passes that screw you over in any of these famous examples are the ones that help code generation in the 99% of remaining cases including many "obvious" optimizations that you'd want the compiler to perform.
I know the situation with undefined behavior is distressing and the examples make it look like the compiler writers are out to get you, but that's not really the case.
Personally I think this was a mistake. A lot of things could be left as implementation-defined instead of undefined: most arithmetic operations, for example. The issue with undefined behavior is that you can’t have it in your program, period. And if you do, your entire program is technically invalid, and the compiler could do unexpected things to it without warning. However, with implementation defined behavior, you can use language constructs (e.g. #ifdef) to choose the correct implementation.