Undefined Behavior and Tricky Expressions (C++ Core #6)
This is the section that matches OA questions most directly: a short program, four options, ask what it prints. Often the correct answer is “undefined” or “the compiler may do anything”, and the reason is an integer conversion, an evaluation order, or a macro. Here is the full checklist.
Three kinds of “not specified”
The standard distinguishes three levels of freedom, and exam answers depend on which one applies.
| Term | Meaning | Example |
|---|---|---|
| Undefined behavior | No requirements at all. The compiler may assume it never happens. | signed overflow, null dereference, out-of-bounds access |
| Unspecified behavior | A valid program, several allowed results, compiler picks one | order of function arguments, value of uninitialized padding |
| Implementation-defined | Compiler must pick and document a behaviour | size of int, char signedness, right shift of negative |
| Ill-formed | The program does not compile (diagnostic required) | missing ;, type mismatch |
UB is not “a random value”. Once the program has UB, the optimizer is allowed to
delete the code path, assume conditions hold, or produce anything. That is why
if (x + 1 < x) can be optimized to false for signed x: the compiler assumes
overflow never happens.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.5cm, minimum height=0.62cm, font=\scriptsize, align=center},
a/.style={->, thick}]
\node[b, fill=red!15] (ub) at (0,0) {UB\\no requirements};
\node[b, fill=orange!15] (un) at (3.2,0) {unspecified\\any allowed result};
\node[b, fill=blue!12] (id) at (6.4,0) {implementation-defined\\documented choice};
\node[b, fill=green!18] (ok) at (9.6,0) {defined\\one result};
\draw[a] (ub) -- (un); \draw[a] (un) -- (id); \draw[a] (id) -- (ok);
\node[font=\scriptsize, anchor=north] at (4.8,-0.6) {increasing guarantees};
\end{tikzpicture}
int x = 1/0; a compile error or UB?ASolution
If both operands are constants, the compiler usually diagnoses it. With runtime operands, division by zero is UB at runtime.
Signed integer overflow
Unsigned arithmetic wraps modulo \(2^N\). Signed overflow is UB.
unsigned u = 0;
u - 1; // 4294967295, defined
int i = INT_MAX;
i + 1; // UB, not INT_MIN
int j = INT_MIN;
-j; // UB: no positive counterpart
INT_MIN / -1; // UB
abs(INT_MIN); // UB
The compiler may exploit the assumption that signed overflow cannot happen:
bool alwaysFalse(int x) {
return x + 1 < x; // optimized to false
}
That is not a bug in the optimizer; it is the contract. If you need wrapping
signed arithmetic, use unsigned types, or -fwrapv (which makes signed overflow
defined as wrap, as a GCC/Clang extension).
long long overflows later but the rule is identical. For sums of \(10^5\) values
up to \(10^9\), use long long; the product side of a comparison is another common
overflow site.
x + 1 < x be compiled to false when x is a signedint?
ASolution
It can only be true if x + 1 overflows, which is UB. The compiler assumes UB
never occurs, so the comparison is always false.
Signed and unsigned comparisons
The usual arithmetic conversions turn a signed operand into unsigned when the unsigned type is at least as wide. Negative values become huge.
int a = -1;
unsigned b = 1;
std::cout << (a < b); // 0 (false): a becomes 4294967295
std::cout << (-1 < sizeof(int)); // 0: sizeof is size_t (unsigned)
Loops are where it bites:
for (unsigned i = v.size(); i >= 0; --i) { } // infinite: i >= 0 always true
for (int i = (int)v.size() - 1; i >= 0; --i) { } // correct, cast once
v.size() is size_t. Subtracting 1 from an empty vector gives a huge number,
not -1:
std::vector<int> v;
// v.size() - 1 -> 18446744073709551615
GCC’s -Wsign-compare warns on the comparison. In an OA, cast size() to int
once when the size is known to fit.
-1 < 1u evaluate to, and why?ASolution
false. The int is converted to unsigned, so -1 becomes 4294967295,
which is greater than 1.
Integer conversions and overflow
Conversions happen silently in assignment, function calls, return statements, and arithmetic.
int i = 3.9; // 3, truncation
char c = 300; // implementation-defined if char is signed: usually 44
unsigned u = -1; // 4294967295
long long bad = 1 << 32; // UB: shift count equals the width of int
long long good = 1LL << 32; // 4294967296
That last pair is a classic: the shift happens in int, and only then is the
result converted. The fix is to make one operand long long first.
Integer promotions: bool, char, short promote to int in arithmetic, so
char a = 100, b = 100; a + b is 200 in int, not an overflow.
Usual arithmetic conversions then pick a common type. The ranking is roughly
int → unsigned int → long → unsigned long → long long → unsigned long long →
float → double → long double, with signedness rules that can surprise.
Conversion from a floating type to an integer type is UB if the value cannot be represented:
double d = 1e20;
int i = d; // UB: out of range
Narrowing conversions are only diagnosed in list initialization:
int x{3.9}; // error: narrowing
int y(3.9); // ok, 3
long long x = 1 << 40; wrong even though the target type is64-bit?
ASolution
The shift is evaluated in int (32-bit) first; 1 << 40 shifts by more than
the width, which is UB. Write 1LL << 40.
Invalid pointer operations
Pointer mistakes that are UB, not just “bad practice”:
int* p = nullptr;
*p = 1; // null dereference
int a[5];
a[5] = 1; // out of bounds
int* q = a + 5; // one-past-end: legal to form
*q = 1; // dereferencing it is UB
int* r = a + 6; // UB even to compute
int* h = new int(1);
delete h;
*h = 2; // use-after-free
delete h; // double free
int x = 0;
delete &x; // UB: x is not from new
int* arr = new int[3];
delete arr; // UB: should be delete[]
char* c = (char*)&x;
*(int*)(c + 1) = 5; // misaligned access
int i = 1;
float f = *(float*)&i; // strict aliasing violation (UB)
Two more that look harmless:
int* p; // uninitialized
if (p) { } // reading it is UB
int* q = new int[10];
q += 10; // one past; q - 20 is UB arithmetic
memcpy is the defined way to reinterpret bytes:
int i = 1;
float f;
std::memcpy(&f, &i, sizeof f); // defined, though the value is a bit pattern
int* p = a + 5; for int a[5] legal?ASolution
Yes, forming the one-past-the-end pointer is allowed. Dereferencing or incrementing past it is UB.
Unsequenced modifications
Two side effects on the same scalar with no sequencing between them is UB. This is the richest source of “what does this print” questions.
int i = 0;
int a = i++ + i++; // UB: two unsequenced increments
int b = i++ + 1; // fine
i = i++; // UB in every standard, including C++17
i = ++i; // fine: the increment happens before the store
int x = i++ + i; // UB: read of i and modification unsequenced
std::cout << i++ << i++; // C++17: defined, prints 0 then 1
That last line surprises people. C++17 sequences the left operand of << before
the right, so the first increment finishes before the second starts. Before C++17
it was UB.
i = i + 1 is fine because the read happens once and the write once, and the
assignment sequences the right side before the left.
The general test: does the expression modify the same object twice, or read it and modify it, without a sequencing relationship? If yes, it is UB.
int x = i++ + ++i; defined?ASolution
No. Both i++ and ++i modify i, and the operands of + are unsequenced.
This is UB in every C++ standard.
Function argument evaluation order
Arguments are indeterminately sequenced since C++17: each argument is evaluated completely before the next, but the order is unspecified. Before C++17 they were unsequenced, so modifying the same variable in two arguments was UB.
int f(int, int);
int i = 0;
f(i++, i++); // C++17: valid, order unspecified (either 0,1 or 1,0)
// pre-C++17: UB
printf("%d %d", i++, i++); // C (and pre-C++17 C++): UB
If the arguments modify different objects, the order does not matter for correctness — only for output order:
int a = 0, b = 0;
f(a++, b++); // fine: different objects
For printf in C, argument evaluation is unsequenced, which is why
printf("%d %d", i++, i++) is the canonical C UB example.
g(i++, i++) compiles and runs under C++17. Is the resultpredictable?
ASolution
No. The order is unspecified, so the two values may appear in either order. The program is valid but its output is not portable across compilers.
Short-circuit evaluation
&& and || evaluate the left side first and skip the right side when the answer
is already known. That ordering is guaranteed and is part of the language.
if (p && p->value) { } // safe: p->value not evaluated if p is null
if (i < n && a[i] > 0) { } // safe: index checked before use
Reverse the first one to p || p->value and the short circuit works against you:
when p is null, the left operand is false, so the right operand runs and
dereferences null.
Short-circuit is also a control-flow tool:
if (n != 0 && total / n > threshold) { } // avoids division by zero
The right operand is not evaluated at all when the left decides the result, so side effects inside it do not happen:
int x = 0;
bool b = false && (x = 1); // x stays 0, right side skipped
bool c = true || (x = 1); // x stays 0, right side skipped
if (p || p->value) a bug?ASolution
When p is null, the left operand is false, so the right operand is evaluated
and dereferences null. p && p->value is the safe order.
Macro expansion pitfalls
Macros are text substitution, with no type checking and no scope.
#define SQUARE(x) x * x
SQUARE(2 + 3) // expands to 2 + 3 * 2 + 3 = 11, not 25
#define BAD_MAX(a, b) (a > b ? a : b)
BAD_MAX(i++, j++) // one argument is incremented twice
#define GOOD_MAX(a, b) ((a) > (b) ? (a) : (b))
Parenthesize every parameter and the whole expression, but even that does not fix
multiple evaluation. Prefer inline functions or templates.
Multi-statement macros need do { ... } while (0) so that an if without braces
does not break:
#define LOG(x) do { print(x); count++; } while (0)
if (ok) LOG(v); // one statement
Other traps:
- Comma in arguments.
#define F(a, b)called asF((1,2), 3)needs the extra parentheses; the comma otherwise splits arguments. - No semicolon issues.
#define TWICE(x) 2*(x)used asTWICE(a);is fine, but inside anifwithout braces it is a hazard. - Stringize and paste.
#xturns the argument into a string,a##bglues tokens. - Precedence.
#define NEG(x) -x;NEG(a) * 2becomes-a * 2, not-(a * 2). - Side effects in conditions.
#define IS_POS(x) ((x) > 0)called withIS_POS(f())callsfonce, which is fine;#define MIN(a,b) ((a)<(b)?(a):(b))withf()calls it twice.
#define SQR(x) ((x)*(x)) with SQR(i++) — what happens?ASolution
i is incremented twice, because the macro substitutes the text twice. This is
undefined behavior when the two modifications are unsequenced.
Operator precedence in expressions
The traps that appear in questions, with their parse:
| Written | Parsed as | Result |
|---|---|---|
a & b == 0 |
a & (b == 0) |
bitwise AND with a boolean |
a << 1 + 2 |
a << (1 + 2) |
shift by 3 |
*p++ |
*(p++) |
dereference old pointer, then advance |
*p = *q++ |
*p = *(q++) |
fine, but easy to misread |
!x == y |
(!x) == y |
compares boolean to y |
a = b = c |
a = (b = c) |
right-associative |
x = a < b ? a : b |
x = ((a < b) ? a : b) |
conditional before assignment |
a ? b : c = d |
(a ? b : c) = d |
often a compile error |
f(a, b) |
function call | comma is an argument separator |
a, b |
comma operator | evaluates a, discards, yields b |
The comma operator is a separate trap: x = (a, b); assigns b, while
f(a, b); passes two arguments. Inside [] in a lambda, commas separate
captures.
When in doubt, parenthesize. It never changes the meaning you intended, and it costs one line of noise.
std::cout << 1 << 2 + 3; print?ASolution
15. + binds tighter than <<, so it prints 1 and then 5 with no separator.
Deep: predict the output
Six small programs, each with the reason.
1. Signed overflow.
int x = INT_MAX;
std::cout << (x + 1 > x); // ?
Undefined behavior. The comparison can be optimized either way; do not answer
1.
2. Unsigned loop.
for (unsigned i = 3; i >= 0; --i) std::cout << i;
Infinite loop. i >= 0 is always true for unsigned, and after 0 it wraps to
UINT_MAX.
3. Signed/unsigned.
std::cout << (-1 < 1u);
0. -1 converts to 4294967295.
4. Unsequenced modification.
int i = 0;
std::cout << i++ + i++;
UB. Two increments of i with no sequencing.
5. Defined chaining in C++17.
int i = 0;
std::cout << i++ << i++;
01 in C++17. Left-to-right sequencing of << makes the first increment happen
before the second.
6. Macro.
#define DOUBLE(x) x + x
std::cout << DOUBLE(3) * 2;
9. It expands to 3 + 3 * 2, not (3 + 3) * 2. Parenthesize the macro and
the arguments.
7. sizeof and side effects.
int i = 0;
std::cout << sizeof(i++) << ' ' << i;
4 0 on a typical platform. sizeof does not evaluate its operand.
8. Shift width.
int x = 1 << 32;
UB. The shift count is not less than the width of int. It is not zero, and it is
not 1.
ASolution
None of the eight. All compile (with warnings, maybe), and the answer depends on runtime behaviour and the standard. That is why they are good exam questions.
Bugs and edge cases
- Assuming two’s complement wrap for signed types. Use unsigned or
long longand check bounds. size()arithmetic.v.size() - 1underflows on an empty container.- Shift by the width.
1 << 32onintis UB, not 0. - Cast before the operation, not after.
(long long)a * b, not(long long)(a * b). - Reading uninitialized variables. Indeterminate values, and now also “erroneous” in some proposals. Initialize.
- Aliasing. Reinterpreting an
int*asfloat*and dereferencing is UB; usememcpy. - Library UB.
vector::operator[]out of range,string::c_str()after modification, iterator invalidation. - Macro side effects. Multiple evaluation of
i++. - Comparing unrelated pointers. Only equality is defined;
<on pointers into different objects is unspecified.
Compiler flags that find these:
g++ -Wall -Wextra -Wconversion -fsanitize=address,undefined -g main.cpp
clang++ -fsanitize=integer -fsanitize=undefined main.cpp
-fsanitize=undefined catches signed overflow, invalid shifts, null dereference,
and misaligned access at runtime. It does not make the program defined; it turns
silent wrong answers into diagnostics.
-O0 and -O2. What is thelikely cause?
ASolution
Undefined behavior. The optimizer exploits assumptions that the UB path never runs, so the two builds are not two valid interpretations of the same program — only one (or neither) is meaningful.
Next: The Preprocessor and Compilation (C++ Core #7) — macros, ODR, and the difference between compile and link errors.