← 🧱 Structs, Unions & Undefined Behaviour
Subtopic 4 of 4

7.4Undefined, unspecified and implementation-defined behaviour

The idea

Undefined behaviour means the C standard places no requirement on what happens. The program may print anything, crash, or seem to work.

Think of it like this: Following a recipe that says "add some salt, or maybe the moon": nobody can tell you what the dish will taste like.

Why it exists

When a question's code does one of these things, the correct option is often "undefined", or compilers disagree.

How it works

  1. Scan the code for out-of-range indexes, null or dangling pointers, and uninitialised reads.
  2. Check for signed overflow and shifts by too many bits.
  3. Look for two modifications of the same variable between sequence points.
  4. Remember: unspecified (argument order) is not the same as undefined; the results are each valid.

Worked example: i = i++ + ++i;

i is modified twice with no sequence point between, so the behaviour is undefined: do not try to compute a single value.

Now play with it

  • →Do the quiz in the lab and note which items are undefined, unspecified or well defined.

What does the C standard say? · question 1 of 10

int a[10]; x = a[10];

Check yourself

Which of these is well defined?

Remember: Undefined = no guarantee at all; unsigned wrap and integer truncation are fully defined.
Exam notes (the dense version)

Undefined: anything may happen. Examples: signed overflow, null or dangling dereference, out-of-bounds access, modifying a variable twice between sequence points (i = i++ + ++i), reading an uninitialised local, a printf format that does not match its argument, shifting by too many bits. Unspecified: argument evaluation order. Implementation-defined: the size of int, the result of right-shifting a negative number.

Previous year questions: Structs, Unions & Undefined Behaviour (2)

PYQs are grouped by topic, so this is the full set for Structs, Unions & Undefined Behaviour; try the ones that match this subtopic. Open all 2 on the topic page.