Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Program won't enter for loop

Alright, so here's the portion of my code that is giving me a problem. What I want it ot do is to take in a grade, decide if it is a valid grade, and then keep asking for a valid number if it is not. However, it won't even enter the loop, so.... any advice? Ive been programming for a little bit but Im still pretty new, so extra explanations are great! Also this is my first time using booleans in a for loop.

for (bool b_valid=false; b_valid=false ; )
{
cin >> n_grade;
b_valid = true;
    if (n_grade>100 || n_grade<0)
        {
            cout << "Invalid grade: Re-enter a number between 0-100 : " << endl;
            cin >> n_grade;
            b_valid = false;
        }
}
like image 204
samuraiseoul Avatar asked Nov 26 '22 23:11

samuraiseoul


2 Answers

Your condition is an assignment: b_valid=false. It will evaluate to false and the loop will never execute. You meant

for(bool b_valid = false; b_valid == false; )
                                 ^^^^ 

There is a coding style which mandates that the constant in comparison be the first argument, like if(false == b_valid). In this case, if you accidentally typed = , you'd get a compiler error. In any case many compiler give a warning in cases where you had written assignment where a boolean expression was expexted. Either yours wasn't as sofisticated, or you just ignored the warning.

like image 93
Armen Tsirunyan Avatar answered Jan 30 '23 01:01

Armen Tsirunyan


I respectfully disagree with the other (woefully upvoted) answers.

Do not compare a boolean value to either true or false.

This is nonsensical, redundant and leads to errors (as in your case).

Simply test the value itself. That is, write ! b_valid.

Furthermore, using a for loop here is blatantly misleading. Use while instead:

while (! b_valid) {
    …
}
like image 31
Konrad Rudolph Avatar answered Jan 30 '23 00:01

Konrad Rudolph