Take the 2-minute tour ×

So I have a do... while statement that is supposed to repeat unless the user enters one of four things. Those four things have a break and they set the variable that controls the while to true, where the default is false. If the user does not enter one of the four answers, the variable will stay false, which should make the do...while start again. It doesn't.

#include <string>
#include <iostream>

using namespace std;

int main()
    int q5_answer = 1;
    int q5_answerU;
    int total_score;
    bool q5_valid = false;

        cout << "Question 5 (#1 is correct)" <<endl;
        cout << "1.) Answer 1" <<endl;
        cout << "2.) Answer 2" <<endl;
        cout << "3.) Answer 3" <<endl;
        cout << "4.) Answer 4" <<endl;
        cin >> q5_answerU;

        switch (q5_answerU)
        case 1:
            cout << "Correct!" <<endl;
            q5_valid = true;
            (total_score = total_score + 1);
        case 2:
            cout << "Incorrect" <<endl;
            q5_valid = true;
        case 3:
            cout << "Incorrect" <<endl;
            q5_valid = true;
        case 4:
            cout << "Incorrect" <<endl;
            q5_valid = true;
            cout << "Invalid answer" <<endl;
    } while (q5_valid = false);
share|improve this question

2 Answers 2

up vote 5 down vote accepted

The condition inside the while is an "accidental" assignment, not a comparison. It needs to read while (q5_valid == false) or more idiomatic while (!q5_valid).

share|improve this answer
Beat me to it!! –  Saladin Akara May 28 '11 at 17:37
Or use while(false == q5_valid) -- this works for other tests than boolean too (42!=answer) and the compiler will automatically catch an accidental assignment –  sehe May 28 '11 at 17:39
@sehe: Better turn on compiler warnings and watch them, please. ;) –  Xeo May 28 '11 at 17:43
@Xeo: what? weren't they already on :) –  sehe May 28 '11 at 17:45
@sehe: I just sends shivers down my spine when someone proposes the yoda conditionals. :( –  Xeo May 28 '11 at 17:47

This is not a boolean expression:

q5_valid = false

It sets the variable q5_valid to false and also returns false. Replace it by:



q5_valid == false

Which are the same. The former is better for readability.

share|improve this answer

Your Answer


