Hacker News new | ask | show | jobs
by flohofwoe 1161 days ago
Undefined Behaviour was a very late 'addition' to C, it only became necessary when C was standardised around 1990. And only after two more decades passed, UB became an actual problem when compiler vendors decided that it's fine to exploit it for optimization tricks.
3 comments

“Decided that it’s fine to exploit it for optimisation tricks” is a poor characterisation. The reality is, if you define particular behaviours you will harm performance in some cases. If you define how something in particular should happen, then all architectures will need to implement that, regardless of their underlying semantics.

eg. C leaves the case of exceeding the size of an int undefined. In most cases it has a predictable effect on modern, mostly similar architectures but that is by no means guaranteed, and forcing an architecture to calculate overflow a particular way seems like a negative.

That being said, everyone has a pet example of a compiler doing some really odd and deep optimisations - I suspect that’s mostly due to successive layers and optimisers adding up to have unexpected effects, rather than a deliberate effort by compiler writers - but I’m no expert on the matter.

> UB became an actual problem when compiler vendors decided that it's fine to exploit it for optimization tricks.

Section 4. Conformance says "A strictly conforming program shall only use those features of the language and library specified in this International Standard. It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any implementation limit."

Compilers are not allowed to produce output dependent on UB for strictly conforming ISO C programs, they must optimize those statements out. Treating UB as impossible is required for ISO C. It's NOT required for GNU C, or Clang C, or Microsoft Visual C, but they usually do so anyway (even though they're not compiling strictly conforming ISO C programs).

Did you miss their point? They merely used UB, correctly, as a term we all do recognize today.

I will utterly kill all humor by explaining it:

They made a funny observation about a thing that happens. The thing that happens is (today) called UB. The funny observation is that that comment kind of exhibited the outward appearance of what the effects of UB could look like.

It began reciting one metaphore, "enough rope to hang yourself" but mid-way unexpectedly switched to a different metaphore "shoot yourself in the foot", producing a combined invalid nonsensical output. As though a program suffered some UB in the routine for looking up and printing metaphores.

The comment author might have done it on purpose. Maybe they intended to make exactly that joke.

The history of the term UB has no more bearing than the history of any of the other words used.