-2

I am a little experienced in field of C# and its compiler set uninitialized variables's value to zero. I found this which is answer for my first question - why C++ doesn't.

But now - how C++ compiler 'chooses' random variable?

I think it's little more interesting/advanced than 'because it works like this'.

10
  • It's not setting it to a random value. It's just not overwriting whatever's there with 0.
    – Joe
    May 21, 2016 at 17:30
  • Ok, but how it works? I create new variable, doesn't set any value, so it have just a memory address. So when I want to print it - from where compiler gets value? Why it is 223 and not 123467?
    – Szkaplerny
    May 21, 2016 at 17:31
  • 1
    The compilers never "choose" the value in an un-initialized variable. When you access the variable you get what is in memory. Blame the "random" value on the operating system or what ever task was using your memory before your program was executed. Residual values in memory. May 21, 2016 at 17:32
  • 1
    Every byte in RAM always holds a value. Without initialization, you get whatever values are left over from the last thing that used that RAM.
    – Wyzard
    May 21, 2016 at 17:34
  • 3
    This is better duplicate than marked one: stackoverflow.com/questions/1422729/…
    – Destructor
    May 21, 2016 at 17:37

2 Answers 2

1

The values aren't "random", they're just whatever happened to be in memory already. That's what it means for a variable to be uninitialized.

8
  • 1
    "they're just whatever happened to be in memory already." That's just not true in general.
    – Baum mit Augen
    May 21, 2016 at 17:36
  • @BaummitAugen: How can you say that?
    – Destructor
    May 21, 2016 at 17:37
  • 1
    @Destructor MSVC explicitly overwrites them with debug values in debug builds, some platforms have "invalid" registers, ... The statement is simply not true.
    – Baum mit Augen
    May 21, 2016 at 17:39
  • 1
    @Destructor I think MSVC uses 0xCCC... or 0xCDCD... or something like this to indicate "not initialized". But sure, setting it to 0 would be just as legal.
    – Baum mit Augen
    May 21, 2016 at 17:41
  • 1
    a) Writing some pattern to memory is not the same as initializing a variable. For instance, an implementation is free to trap on such a pattern interpreted as double (can't happen on properly initialized doubles), pointers would still be invalid, ... b) This still does not address implementations that do not silently ignore reads on uninitialized memory.
    – Baum mit Augen
    May 21, 2016 at 18:02
0

This is implementation dependant, but typically the compiler doesn't choose any value for the variable. Instead the compiler allocates space on the stack where the variable will be stored - but it doesn't put any value there. So if you read the uninitialized variable, you will probably get whatever happened to be on the stack beforehand.

Not the answer you're looking for? Browse other questions tagged or ask your own question.