skip to content

In C++, what happens when a function reads a local int it never initialized, and how does C++26 erroneous behaviour change that?

level: seniorimportance: should knowfreq 40%

answer

  1. indeterminate value before C++26
  2. statics are zero-initialized anyway
  3. erroneous: defined but wrong
  4. [[indeterminate]] opts back out
  5. new int stays indeterminate

basics

~20 s

Up to C++23, reading an uninitialized local int produces an indeterminate value and is undefined behaviour. C++26 gives such locals an erroneous value: reading it is erroneous behaviour, well-defined but diagnosable, unless the variable is marked [[indeterminate]].

solid answer

~40 s

An automatic `int` with no initializer starts with an **indeterminate value** in C++23, and producing that value by reading it is **undefined behaviour**; statics and thread-locals are zero-initialized, so they are not affected. C++26 changes automatic variables: their bytes start with an **erroneous value** chosen by the implementation, independent of program state, and reading it is **erroneous behaviour**: well-defined, but a bug the implementation is recommended to diagnose and is permitted to stop the program for. The compiler can no longer reason as if the read never happens. `[[indeterminate]]` on the variable restores the old indeterminate rule for performance-sensitive buffers, and dynamic storage such as `new int` keeps it too. The fix is unchanged: initialize the variable.

code

cpp · 17 lines
cpp
#include <cstdio>
#include <memory>
#include <vector>

int checksum(const unsigned char* data, int n) {
    int sum = 0;                    // initialized: no indeterminate read
    for (int i = 0; i < n; ++i) sum += data[i];
    return sum;
}

int main() {
    const unsigned char bytes[] = {1, 2, 3};
    static int calls;               // static storage: zero-initialized
    auto p = std::make_unique<int>();   // value-initialized: 0
    std::vector<int> v(3);          // elements value-initialized: 0
    std::printf("%d %d %d %d\n", checksum(bytes, 3), calls, *p, v[2]);
}

go deeper

for a junior

Recall that a local int without an initializer must not be read before it is assigned, while statics and globals start at zero.

for a middle

Explain indeterminate values, why reading one is undefined rather than merely random, and which initialization forms produce zero.

for a senior

Describe C++26 erroneous behaviour precisely: implementation-chosen value, permitted diagnosis or termination, the [[indeterminate]] opt-out and the heap exception.

for a principal

Judge where the C++26 default trades a little speed for safety, and when a team should allow [[indeterminate]] on a measured hot buffer.

## Up to C++23: an indeterminate value When storage for an object with automatic storage duration is obtained and no initialization is performed, its value is **indeterminate**. Producing that value, by reading the variable in an expression, is **undefined behaviour**. A small, deliberate set of exceptions lets values of type `unsigned char` and `std::byte` carry indeterminate bytes through a copy, so a byte-by-byte copy of a partly initialized object is allowed; an `int` gets no such exception. Which variables are affected: - **Automatic** locals without an initializer: `int sum;`, `double d;`, a `struct` whose members have no default member initializers. - **Dynamic** objects default-initialized by `new int` or `new int[n]`. - **Not** variables with static or thread storage duration: those are zero-initialized before anything else runs. - **Not** value-initialized objects: `int sum{};`, `int sum = 0;`, `new int()` and `std::vector<int> v(n)` all start at zero. Because reading the value is undefined, an optimizer may assume it never happens, so the "random number" you expect is not even guaranteed to be stable from one read to the next: nothing requires `x > 5` and a later `x <= 5` to disagree, and code built on either test can misbehave in ways no single garbage value would explain. ## C++26: erroneous values and erroneous behaviour C++26 adds a new category beside undefined behaviour. **Erroneous behaviour** is defined as well-defined behaviour that the implementation is recommended to diagnose; it is always the consequence of incorrect code. The rule for automatic variables changed accordingly: 1. The bytes of an automatic variable without an initializer start with an **erroneous value**, determined by the implementation independently of the state of the program, so it does not depend on what an earlier stack frame left behind. 2. Reading it is **erroneous behaviour**, and the result of the evaluation is that erroneous value. 3. The implementation is permitted to issue a diagnostic and permitted to terminate the program at that point, so sanitizers and checking builds can still stop on it. 4. A note keeps one corner undefined: if the erroneous value is not a valid value for the type, the lvalue-to-rvalue conversion is still undefined behaviour. | Case | C++23 | C++26 | |---|---|---| | `int x; return x;` | undefined behaviour | erroneous behaviour | | `int x [[indeterminate]]; return x;` | (attribute does not exist) | undefined behaviour | | `int* p = new int; return *p;` | undefined behaviour | undefined behaviour | | `static int s; return s;` | `0` | `0` | The draft's example shows both sides: ```cpp // C++26 only: not supported by Apple clang 21, which ignores the attribute with a warning void f(int); void g() { int x [[indeterminate]], y; f(y); // erroneous behavior f(x); // undefined behavior } ``` ## What implementations do with it The standard deliberately leaves the erroneous value to the implementation. GCC 16 documents that in `-std=c++26` mode, when `-ftrivial-auto-var-init=` is not given, automatic variables are zero-initialized; that is one implementation's choice, not a promise that the value is zero. Apple clang 21 does not implement the C++26 attribute and warns `unknown attribute 'indeterminate' ignored`. Code that must build as C++17 or C++20 gets none of this and keeps the undefined behaviour. ## What a reviewer should still insist on - **Initialize at the declaration**: `int sum = 0;` or `int sum{};`. Erroneous behaviour makes the bug survivable, not correct; the result is still wrong. - **Treat compiler warnings as errors** here. Apple clang 21 with `-Wall` reports `variable 'sum' is uninitialized when used here [-Wuninitialized]`, and `-Wsometimes-uninitialized` for a variable set on only one branch. - **Use `[[indeterminate]]` only** where measurement shows that the compiler's initialization of a large local buffer costs real time, and then fill the buffer before any read. - **Do not lean on it for heap memory**: `new T` and `malloc` storage stays indeterminate. - **Give class members default member initializers**, such as `int count = 0;` inside the class, so that every constructor, including ones added later, starts from a known value. The interview point is the shift in category: C++26 does not make the variable initialized, it removes the optimizer's licence to treat the read as impossible.

  • Does C++26 make reading an uninitialized heap object safe too?
    No. The erroneous-value rule covers objects with automatic storage duration that are not marked `[[indeterminate]]`. Storage obtained for dynamic objects, such as `new int` or `new int[n]` without an initializer, still starts with indeterminate values, so reading one remains undefined behaviour. Value-initialize with `new int()` or use `std::make_unique<int>()`.
  • Why did C++26 add [[indeterminate]] instead of simply zero-initializing every local?
    Zero-initialization would make an uninitialized read look like correct code and hide the bug from tools. The erroneous value keeps it diagnosable while ending the undefined behaviour. `[[indeterminate]]` exists because initializing a large stack buffer that the code fills immediately costs time, so the attribute lets that case opt back into the old rule explicitly.

  • An uninitialized local int just holds whatever garbage was on the stack.
  • C++26 zero-initializes every local variable, so initializers are now optional.
  • Static and global ints without an initializer are uninitialized too.
  • Erroneous behaviour is another name for undefined behaviour.
  • C++26 also fixes reads of memory from new int without an initializer.

Assumes C++23 for the undefined-behaviour rule; erroneous values and the [[indeterminate]] attribute are C++26 and only partly implemented.