Tech News
← Back to articles

Undefined Behavior in C and C++

read original related products more articles

Undefined behavior in C and C++

Photo by Jonathan Kemper on Unsplash

What is undefined behavior?

February 3, 2024Working in C or C++ requires some awareness of: what it is, what its effects are, and how to avoid tripping over it. For simplicity, I will just talk about C, but everything in this article also applies to C++ except where otherwise noted.It is, generally speaking, more difficult to program in C than in the likes of Python.

In some ways, that's because C is a lower-level language, closer to assembly; it just gives you what the underlying machine gives you.

For example, Python integers behave like their mathematical counterparts. They are unbounded; adding integers will always give you the right answer, no matter how large. (Unless, of course, the computer runs out of memory. No language can conjure infinite resources. But it can and does guarantee that you will either get the right answer, or a crash. Never the wrong answer.)

C integers are what fits in a CPU register. The + operator performs a single CPU add instruction. If that overflows a machine word, it will give something other than the right answer.

int successor(int a) { // May or may not be correct return a + 1; }

int

int

... continue reading