E
E
Evsign2014-09-24 20:52:40
C++ / C#
Evsign, 2014-09-24 20:52:40

Why does an uninitialized variable have a value of 0?

I am reading a book on C++ Primer 5th edition (Stanley Lippman, Josée Lajoie, and Barbara E. Moo).
It says that if a variable is declared outside the function, then it is automatically initialized with the value 0, and if the variable is declared inside the function, then it will not be initialized and will contain the value undefined. This is about build-in types.

#include <iostream>
using namespace std;
int a;
int main(){
  int b;
  cout << a << " " << b << endl;
}

Why then does this code output
0 0
?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
L
Lolshto, 2014-09-24
@Evsign

Because that's how the stars are aligned. Potentially, the output can be anything, which is why it is undefined. Zero - included in many different options

A
Alexander Taratin, 2014-09-24
@Taraflex

In c++ there is no undefined, there is only NULL the same 0 or nullptr.

T
tsarevfs, 2014-09-24
@tsarevfs

There is no special meaning of undefined. This means that the compiler can do whatever it wants with it. In 2008 studio output 0 1 for example.

M
MacDag, 2014-09-25
@shatov

Because they have default values. and the default is zero.

T
Trrrrr, 2014-10-01
@Trrrrr

Compile the program in release.
In debugging, the compiler resets.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question