Curiosity: TripleX Code Question

Greetings,

While I was following along in video 23. User Input, I made a mistake by putting all my Guess variables in one spot in my code and came up with an interesting answer. I typed in :

int GuessA, GuessB, GuessC;
int GuessSum = GuessA + GuessB + GuessC;
int GuessProduct = GuessA * GuessB * GuessC;
std::cin >> GuessA >> GuessB>> GuessC;

When I entered my 3 digit code, we’ll say “3 4 5”, I got:

You entered:345
The sum of 3 4 5 is 14807482
The product of 3 4 5 is 1623023616

But when I fixed it up I got what I was looking for. Seeing the importance of Hierarchy, could anyone explain how I got the larger calculation?

In that code Guess[A-C] are uninitialised. Reading the value of an uninitialised variable is “undefined behaviour” (aka UB) which is what you are doing on the following two lines.

UB simply means the standard doesn’t define what’s supposed to happen so quite literally anything could happen. The program could have foreseen what you were going to enter and give you the expected results. Or maybe 0 for everything. Though It probably just used whatever junk value was there in memory.

Expanding on Dan’s “whatever junk value was there in memory” -

When you declare a variable like GuessA, the computer picks a memory address, adds the size of “int” in bytes(probably four bytes), and reserves that four byte block of physical memory for the variable.

Any ones or zeroes that previously occupied that block of memory, from the address to the end of the following four bytes, are not erased or modified. The previous data could have been anything, but the value of the ones and zeroes in those four bytes, interpreted as if they were an “int”, were probably what your program used in its calculations.

Neat,

Are there any cases where something like that might have a use?

No and is security concern, always initialise your variables.