-6

Why uninitialized variable print a strange negative value ?

int x;
cout << x << endl;
faressoft
  • 19,053
  • 44
  • 104
  • 146
  • 8
    Because it's uninitialized. It's whatever bytes happen to be at that place in memory already. – Wyzard Apr 28 '12 at 16:36
  • 1
    basically that x points to a memory location which could have previously been filled. You are probably seeing that value. – Hunter McMillen Apr 28 '12 at 16:36
  • because that variable is actually a location in the system memory somewhere, and unless YOU put something into that location, you'll get whatever garbage is left in that spot from the LAST time that memory location was used. – Marc B Apr 28 '12 at 16:36
  • @Wyzard: " It's whatever bytes happen to be" Actually this isn't right either. During debug build compiler can fill unitialized variables with some value (0xcccccccc). So there's "some" value in unitialized variable, but it is hard to say what it'll be. – SigTerm Apr 28 '12 at 16:41

3 Answers3

13

What you're doing (reading the value of an uninitialised variable) is undefined behaviour; anything can happen, from it appearing to work, to printing random values, to crashing, to buying pizza with your credit card.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
5

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.

  • 2
    Formally, it has an "indeterminate value", meaning that even trying to read it may fail (in a more or less spectacular way). – Bo Persson Apr 29 '12 at 15:30
0

When a variable is not initialized , it shows you "Garbage Value". What that mean is it can be any arbitrary number from anywhere, may be from another running application or random number from big pool of memory.

Faizan
  • 1,847
  • 8
  • 40
  • 63