Hacker News new | ask | show | jobs
by nicoburns 1130 days ago
You can have it for reasons other than memory safety, for example signed integer overflow is UB in C and C++ (but not in Rust). However, higher level languages typically go to great lengths to avoid it. For example, in Java you will get a NullPointerException rather a null pointer actually being dereferenced, which immediately rules out any UB due to a pointer being dereferenced where doing so is not allowed.
1 comments

Wow signed overflow is UB? I would have assumed it was defined, it just allows overflow.

And I am assuming something like the NullPointerException comes with a huge performance hit? Otherwise I assume every systems language would do something similar.

I cannot think of a useful way to define signed overflow. I can make it do something, but at the end of the day no matter how you define it, if it happens in the real world your program has a bug.

Since we can be sure if it ever happens your code has a bug, making it undefined is a good thing: the compiler can then assume it doesn't happen and so back track to prove some other things can't happen and so make your program run a little faster.

I'd much rather have a bug in my program than UB. At least the bug is easy to track down and fix, and is limited in scope to the line of code that contains the error.
You sacrifice speedy code for this case that probably won't even happen and so you probably won't have to debug anyway. Is it really worth it?
> Wow signed overflow is UB? I would have assumed it was defined, it just allows overflow.

Presumably it's not defined because the behaviour depends on the signedness representation.