Yvain
Yvain

Reputation: 29

Logical OR precedence

I have tried writing a loop that would refrain the user to enter a wrong kind of data (actually a boolean) into the program by using the || operator.

int Entrer() 
{
    int A;
    do
    {
        cout<<"Entrez 0 ou 1."<<endl;
        cin >> A;
    }
    while (A != (1 || 0));
    return A;
}

Can somebody tell me why the program only accepts 1 and no 0 ?

Upvotes: 1

Views: 61

Answers (2)

wolfPack88
wolfPack88

Reputation: 4203

If you want to accept 1 and 0, you need to write the conditional as while(A != 1 && A != 0);. As your conditional written, it will evaluate the (1 || 0) first, and, as 1 is true and 0 is false, will evaluate to A != 1.

Upvotes: 0

timrau
timrau

Reputation: 23058

do { ... } while (A != (1 || 0));

It should be while (A != 1 && A != 0);

Otherwise, A != (1 || 0) stands for A != 1 since (1 || 0) is evaluated before !=.

Upvotes: 2

Related Questions