Hacker News new | ask | show | jobs
by yeputons 1025 days ago
My main advice: never trust C, C++, or their compilers. Undefined behavior bites. Even if you just care about the latest 64-bit Ubuntu Linux LTS, compiler updates or flag changes bite as well.

That's the main difference between C and C++ and almost any other language. Not the syntax, neither the perceived "low-levelness", nor manual memory management. In any other language, if you make a mistake, the program behaves badly, but in a predictable way. In C and C++ it may behave reasonably, it may crash in another file altogether few seconds after the erroneous line is executed, it may produce the correct answer. Or it may crash only sometimes. Or it may silently produce an incorrect answer. Different behaviors on different systems, and even on the same system with different compiler flags (e.g. optimization level), of course.

That makes reliable experiments with C and C++ impossible. Even if you have just five lines of code, you almost never know if they're valid C or C++ for sure (separately, whether they do what you want with modern/legacy compilers). It's still fun and everything (congrats on making your own language, that should've been fun!), but you never truly know whether what you wrote is not going to break in a few years (or months) with zero code modifications just because there was another UB lurking around.

See https://evan.nemerson.com/2021/05/04/portability-is-reliabil... if you're curious about more practical implications.

1 comments

I suppose this is one of those things where people’s experiences vary widely, but FWIW after 20 years of writing C/C++, I can count the number of times this has bitten me on one finger. And even then, I still think it was more likely just an optimizer bug in the god-awful compiler.
Yes, I think it heavily depends on what you're doing and your mindset.

E.g. if you work with a single compiler on a single platform all the time and expect the compiler to "just compile the code", then you're likely to learn all its quirks, avoid them automatically, use proper abstractions/contracts/invariants to guard against incorrect code, etc. Moreover, you likely know how exactly the most popular UB shows itself with your compiler.

If you juggle compilers all the time and work with not-so-high-quality code (legacy or not), especially the one with little tests, I expect UB to pop up a lot. Or even if you just test on one platform and do final runs on another, that happens all the time in competitive programming or home assignment grading, especially with beginners.