Needing clarification on why a while loop is running while value is true

Hi there. I'm currently studying C++ from a book by D.S. Malik and I had a question regarding the following portion of code that was used as an example. This code is a number-guessing game, in which the user attempts to guess a generated number between 1-100, and uses a flag-controlled while loop.

isGuessed is the bool variable, which has been declared as false. I'm confused as to why the while loop is only executing while isGuessed is true (!isGuessed). If the number isn't guessed, why is it prompting the user to enter guesses only while isGuessed is true? Is there something I'm misunderstanding? I can post the full code if it is needed for clarification.

This is the excerpt that I was confused about:

1
2
3
4
5
6
7
8
9
     isGuessed = false; 

     while(!isGuessed)
     { 
          cout << "Enter an integer greater than or equal to 0 and "
               << "less than 100."; 
          cin >> guess; 
          cout << endl; 


Thank you.
Last edited on
You are trying a little too hard. isGuessed is indeed false. What this line says:

1
2
3
4

    while( ! isGuessed )      /*    Means while not guessed    */



I bet in the code where the number is guessed, the code sets isGuessed to true, causing the loop to terminate.

Let us know if you still need help; otherwise, please marked this as solved.

Good luck!
Yes, that's correct. I was just confused that even if isGuessed declared false, !isGuessed doesn't mean the opposite, which is true? That's where my confusion is.
Right! When starting out, it is easy to get confused between assignment and comparison. Another way that might not be as confusing could be:

1
2
3
4
5
6
7
8

    bool looping = true;

    while( looping )
    
        // The rest of your loop



Of course in this case, you would set looping to false to quit the loop. Sometimes coders just use the break statement to get out of a loop, but that's not my style.
Okay. So the ! operator just means that the variable is false. Even it's declared as false already, !variable doesn't make it true, correct? Thank you for your patient responses.
Correct: In this case, the statement literally means, while( isGuessed == false ); the '!' negates (gives the opposite of) the variable being tested.
Thank you so much!
Topic archived. No new replies allowed.