Comment

Comment by Veserv

Undefined behavior is just what happens when you violate a mandatory precondition.

if (x > 0) {…}. But what if you entered the body when x <= 0?

if (false) {…}. But what if you execute the body?

These are “impossible”. What happens when the impossible occurs is “undefined”.

When the older standards said signed integer overflow for addition is undefined what they are actually saying is that the real definition of + is:

    int +(int x, int y) { 
      assert(in_range(actual_math_add(x, y), signed_int_min, signed_int_max));
      return machine_add(x, y);
    }
So of course what happens when you get signed overflow is undefined; you should hit that assert and your program should explode and die. You should “never” get to the next instruction.

But, in the interest of performance, “release mode” (which in this case is just any compilation) elides asserts since as a programmer you should not write code that asserts in much the same way that you should not write assert(false) in a normal code path that is supposed to run. Assertions are intended for “impossible” code paths and usually get compiled out in “release mode” though maybe your code is buggy and can actually hit them and then your program goes off the rails because it had a bug.

Put another way, if you did write assert(false) in a regular code path, would you find it unreasonable for the compiler to just delete the code after it? That is what undefined behavior is for.

parent Veserv 22 days ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton