Instead, if you dislike undefined behavior, I challenge you to come up with workable semantics for non-gratuitous scenarios, of which I'll lay out three. Remember, if it's not undefined, then there are some defined semantics that need to be preserved, even if implementation-defined, so you should be able to explain those semantics. If you can't find such semantics, then maybe undefined behavior isn't such a bad thing after all.
The first case is the compiler hint. A function marked _Noreturn returns. Or you alias two pointers marked restrict. Remember that the entire point of these hints is to permit the compiler to not generate code to check for these scenarios.
The second case is uninitialized memory. You've probably already come up with such semantics, so I'll point out an optimization scenario that you probably don't object to that your semantics didn't cover:
static int y; /* uninitialized */
_Bool cond = f();
int x = cond ? 2 : y; /* Is it legal to fold this to int x = 2; ? */
Hopefully, you'll agree that that is a reasonable optimization. Now consider this code: static int y; /* uninitialized */
_Bool cond1 = f(), cond2 = g();
int x1 = cond1 ? 2 : y; /* So int x1 = 2; */
int x2 = cond2 ? 3 : y; /* So int x2 = 3; */
if (!cond1 && !cond2) {
assert(x1 == x2); /* Uh... */
}
This is just scraping the tip of the surface of uninitialized values. Developing sane semantics around these sorts of values that also allow reasonable optimizations is challenging. You can look at the very lengthy saga that is undef, poison, and freeze in LLVM (still ongoing!) to see what it looks like in practice.The third category is traps. Let's pick an easy example: what happens if you dereference a null pointer? Now let's consider the consequences of those semantics on some more code examples:
int *x = NULL;
int *y = &*x; /* Can this be lowered to int *y = x; ? */
size_t offset = (size_t)&((struct foo *)NULL)->field; /* Remember, x->a is actually (*x).a */
int *z = get_pointer();
*z; /* No one uses the result of the load, can I delete it? */
for (int i = 0; i < N; i++) {
foo(*z); /* Can I hoist the load out of the loop? */
}
Note that all of the optimizations I'm alluding to here are ones that would have existed all the way back in the 1980s when C was being standardized, and these are pretty basic, pedestrian optimizations that you will cover in Compilers 101.