Reputation: 11
This code should not work since guess isn't initialized but the instructor in this youtube video I had been watching managed to run this code without any problems. May I know the reason why I cannot seem to run the code but he can?
Video link with time == https://youtu.be/vLnPwxZdW4Y?t=8615
int main() {
int SecretNum = 7;
int guess;
while(SecretNum != guess) {
cout << "Enter guess: ";
cin >> guess;
}
cout << "You win!";
return 0;
}
Upvotes: 1
Views: 78
Reputation: 2457
If you do not initialize a variable, the compiler will not do it for you. Whatever data happens to be stored at that memory address will be the contents of the variable, interpreted as an integer.
Depending on the compiler and the settings you use, different things might occur. With a default g++ compiler, you may get a warning about using an uninitialized variable. If you have the option to treat warnings as errors, the program will not compile.
Either way, since this is undefined behavior, the program may do whatever it pleases. Including connecting to your bank and transferring all your money to me. Or creating a wormhole to Andromeda. Don't do UB please. Realistically, it will work as intended unless guess
happens to be initialized with 7, for which the chance is distinctly very slim. Or, in other words, it should work most of the time.
Since most of the time is not what you want, unless of course you want to practice the debugging skills of your coworkers, you should avoid this.
Whenever there is undefined behavior, the compiler will most likely do the simplest thing, in this case it does nothing.
Upvotes: 1
Reputation: 595742
This code should not work since guess isn't initialized
Correct. The code has undefined behavior. I have posted a comment on the video stating as much.
but the instructor in this youtube video I had been watching managed to run this code without any problems.
Purely by luck only.
May I know the reason why I cannot seem to run the code but he can?
An uninitialized variable has an indeterminate value from whatever random data previously occupied the variable's memory. So, the variable could very easily have ended up with an initial random value of 7 and broken the loop prematurely, which is probably the case in your environment, but not in his. Thus is the nature of Undefined Behavior.
Upvotes: 1
Reputation: 3396
In C++, local variables are not initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. However, it is not an error to have uninitialized variables. So the program will compile and run.
Upvotes: 0