Large number returned when GuessC is not assigned a value

Hi there, I made a mistake when following along from the lecture where I accidentally wrote GuessB twice in the std::cin statements, which can be seen below:

    int GuessA, GuessB, GuessC;

    std::cin >> GuessA;
    std::cin >> GuessB;
    std::cin >> GuessB;
    std::cout << "You entered: " << GuessA << GuessB << GuessC << std::endl; 
 

Obviously I needed to change one of them to read std::cin >> GuessC. What I found strange though, is that my code did not crash. Instead when I entered an example code e.g. “2 3 4”, the console returned a large number of 7/8 digits instead of any of the user input values. My guess is that as I am declaring a variable ‘GuessC’ and printing it to the console in the final line of my example code, that the code gets confused as there is nothing left in the input stream for it to access, so it instead pulls a value from outside of the allocated memory space. Is this correct at all? If not I’d be really interested in finding out why this is happening as I find it to be very intriguing.

GuessC is uninitialised.

Reading the value of an uninitialised variable is “undefined behaviour” which means the standard doesn’t say what should happen meaning quite literally anything can happen.

So what you wrote could print a random value, print what you actually intended, crash your program, dispense money out of your CD drive, eradicate COVID, anything.

…Obviously some of those results are more likely than others.

Ah I see. My follow up question would have been “Why not just initialise all Guess variables to be 0?” but from what I am seeing online, while initialising variables ASAP is a good idea, as the Guess values are being assigned to the input stream given by the user (assuming no silly typos are made!) this undefined behaviour issue shouldn’t be a problem

Right. Initialising it to a value and then immediately overwriting it on the next line before it even has a chance of being read shouldn’t really be problematic only problem I can think of off the top of my head is typos.

OTOH, On GCC it amounts to 1 extra instruction which is not going to be noticeable under 99% of situations.

https://godbolt.org/z/KE1E76

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms