Many aptitude tests ask for the output of code such as i = i++ + ++i;. Explain what undefined behaviour means in C, why this expression has no correct answer, and list other common sources of undefined behaviour.
Show the explanation
Undefined behaviour (UB) means the C standard places no requirement at all on what happens. The program may print what you expect, print something else, crash, or change from run to run or compiler to compiler. Optimisers are allowed to assume UB never happens, so the results can be surprising, such as whole checks being deleted.
Why `i = i++ + ++i;` has no answer. The expression changes i more than once (two increments and an assignment), and the standard does not order these changes relative to each other. C11 calls them unsequenced side effects; older texts say there is no sequence point between them. Modifying the same object twice without sequencing is UB. GCC and Clang can give different numbers, and both are "correct". The right interview answer is: "This is undefined behaviour; there is no defined output. I would rewrite it as separate statements." gcc -Wall warns about it (-Wsequence-point).
Other common UB
- Signed integer overflow, such as
INT_MAX + 1. Unsigned arithmetic wraps around and is well defined. - Reading or writing outside an array, including one past the end with
*. - Dereferencing a NULL, dangling or uninitialised pointer.
- Using an uninitialised local variable's value.
- Shifting by a negative amount or by at least the width of the type (
1 << 32for a 32-bit int). - Modifying a string literal (
char *s = "hi"; s[0] = 'H';). - Freeing twice, or freeing memory that malloc did not give you.
- Calling
printfwith a format that does not match the arguments.
Related but different:
- Unspecified behaviour has a set of allowed results and the compiler picks one. Example: the order in which function arguments are evaluated.
- Implementation-defined behaviour is unspecified behaviour that the compiler must document. Examples:
sizeof(int), or right-shifting a negative number.
Practical defences: compile with -Wall -Wextra, and test with -fsanitize=undefined,address.
Original UniCircle question. Last reviewed 22 Oct 2026.
