Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do uninitialized objects of built-in type defined inside a function body have undefined value?

Question:
Why do uninitialized objects of built-in type defined inside a function body have undefined value, while objects of built-in type defined outside of any function are initialized to 0 or ''?

Take this example:

#include <iostream>
using std::cout; using std::endl;

int ia[10];                   /* ia has global scope */

int main() 
{
    int ia2[10];              /* ia2 has block scope */

    for (const auto& i : ia)
        cout << i << " ";     /* Result: 0 0 0 0 0 0 0 0 0 0 */

    cout << endl;
    for (const auto& i : ia2)
        cout << i << " ";     /* Result: 1972896424 2686716 1972303058 8
                                 1972310414 1972310370 1076588592 0 0 0 */
    return 0;
}
like image 611
Andreas DM Avatar asked Nov 05 '14 13:11

Andreas DM


People also ask

What happens if we use an uninitialized variable where it is declared but no initial value is given?

An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.

What is the value of uninitialized variable?

An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.

What is an uninitialized variable SET TO LET result What is result?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.

What happens when variables are not properly initialized?

If you don't initialize an variable that's defined inside a function, the variable value remain undefined. That means the element takes on whatever value previously resided at that location in memory.


1 Answers

Because one of general rules of C++ is that you don't pay for what you don't use.

Initializing global objects is relatively cheap because it happens only once at program startup. Initializing local variables would add overhead to every function call, which not everybody would like. So it was decided to make initialization of locals optional, the same way as in C language.

BTW If you want to initialize your array inside a function, you can write:

int ia2[10] = {0};

or in C++11:

int ia2[10]{};
like image 133
Anton Savin Avatar answered Sep 22 '22 00:09

Anton Savin