Skip to content

What Happens If You Use an Uninitialized Variable in C++

In this guide
  1. What an uninitialized variable is
  2. What undefined behavior means
  3. It may look like it works
  4. What compilers tell you
  5. Not every variable is the same
  6. A note on newer C++
  7. The fix

Short answer

If you declare a local variable such as int n; and read it before giving it a value, the program has undefined behavior. The variable holds whatever happened to be in that memory, and the C++ language puts no limits on what the program may then do. The fix is simple: give every variable a value when you create it.

What an uninitialized variable is

learncpp.com explains that C and C++ do not automatically initialize most variables to a given value. A variable that has not been given a known value is uninitialized, and its value is whatever (garbage) value happens to already be in that memory address.

cppreference describes it in the language's own terms. For a plain int, default initialization performs no initialization, and the object retains an indeterminate value until that value is replaced. Using an indeterminate value in most ways is undefined behavior.

What undefined behavior means

cppreference's page on undefined behavior says: there are no restrictions on the behavior of the program. It lists memory accesses outside array bounds, signed integer overflow and null pointer dereference among its examples, and says implementations are not required to diagnose undefined behavior, and the compiled program is not required to do anything meaningful.

For uninitialized variables the page shows this directly:

bool p; // uninitialized local variable
if (p)  // UB access to uninitialized scalar
    std::puts("p is true");
if (!p) // UB access to uninitialized scalar
    std::puts("p is false");

The possible output it lists is both p is true and p is false. Both messages can print, which no honest program could ever do. That is what "no restrictions" looks like in practice.

It may look like it works

Because the value is whatever was already in memory, the same program can print 0 on one run, a strange number on another, or behave differently with different compiler settings. The cppreference page also notes that compilers may produce unexpected results when a program with undefined behavior is compiled with optimization turned on. So "it printed 0 when I ran it" is not evidence that the code is correct. Compare the way reading past the end of an array can also appear to work, covered in what happens past the end of an array in C++. A crash, if it comes, is the lucky outcome, as what is a segmentation fault explains.

What compilers tell you

learncpp.com says most modern compilers will attempt to detect if a variable is being used without being given a value, and will generally issue a compile-time warning or error. That is a good reason to read your compiler warnings and not ignore them. It does not catch everything, so you should not rely on it.

Not every variable is the same

cppreference's example shows that where a variable lives matters:

int n;            // static (namespace scope): zero-initialized to 0

int main()
{
    int n;        // automatic: the value is indeterminate
}

A variable declared outside any function, at namespace scope, is set to zero before the program runs. A local variable inside main is not. So an int declared at the top of a file and an int declared inside a function behave differently, which catches many beginners.

A note on newer C++

cppreference says that since C++26, the value of an uninitialized automatic variable is an erroneous value, and using it is erroneous behavior, which the implementation is recommended to diagnose and which can end the program. This depends on your compiler version and language standard. Do not rely on it. The safe habit is the same under every standard.

The fix

learncpp.com's advice is that you should always initialize your variables, and it calls that the primary reason for the best practice. Write it when you declare it:

int n = 0;   // copy initialization
int m{0};    // brace initialization

If you do not know the value yet, wait to declare the variable until you do, or give it a clear starting value such as 0.

C++ Game: Segfault

Teaches C++ to complete beginners as a game where you tap one real line of code at a time.

Get it on Google Play

Free to play. Halls 1 to 4 are free with no time limit, and free players can watch optional rewarded video ads for bonuses. Segfault Pro, a monthly subscription or a 3-month pass paid once, opens hall 5 and up, unlimited practice sets and mock exams, with no ads.

Segfault teaches C++ to complete beginners as a game. Each card shows a box and the value it needs, and you tap the one real line of C++ that makes the box match, then watch the value fly in. Every line is compiled and run with a real C++ compiler. You do not type, so it will not turn you into a programmer on its own, but it helps you see what a line does to the value a variable holds.

Sources

  1. Uninitialized variables and undefined behavior - learncpp.com
  2. Default initialization - cppreference.com
  3. Undefined behavior - cppreference.com

Search the site