Namespaces
Variants
Views
Actions

Uninitialized variables

From cppreference.com


It is possible to create a variable without a value. This is very dangerous, but it can give an efficiency boost in certain situations.

To create a variable without an initial value, simply don’t include an initial value:

// This creates an uninitialized int
int i;

The value in an initialized variable can be anything – it is unpredictable, and may be different every time the program is run. Reading the value of an uninitialized variable is undefined behaviour – which is always a bad idea. It has to be initialized with a value before you can use it.

#include <iostream>
 
int main()
{
    int i; // uninitialized variable
 
    // WARNING: This causes undefined behaviour!
    std::cout << i << '\n';
 
    i = 23; // initializing the variable
 
    // Now it is safe to use.
    std::cout << i << '\n';
 
    return 0;
}

The value printed on the first line in the example above can be anything.

Normally uninitialized variables are a bad idea, and the only place where they are useful is when you are about to read the variable in from some input stream.

#include <iostream>
 
int main()
{
    std::cout << "Enter your age: ";
 
    int age; // uninitialized
 
    // This reads a value from standard input, and uses it to
    // initialize the variable.
    std::cin >> age;
 
    std::cout << "Your age is: " << age << '\n';
 
    return 0;
}

Not initializing the variable like this:

int x;
std::cin >> x;

is slightly more efficient than:

int x = {};
std::cin >> x;

because the latter sets x to the value 0 then discards that value a moment later when the input happens, whereas the former does not do those extra, wasteful steps. (In practice, though, the time taken to input is usually so much greater than the time wasted by the superfluous initialization that there is no real noticeable difference between the two, and it comes down to style preference.)