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;
}
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.
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.
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.
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.
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]{};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With