Search code examples
clogical-operatorslogical-orlogical-and

||, && operators in C


Why this code only work with && operator?

I think it should be ||, but I'm wrong. Choice can not be equal to 2 value at the same time?

I need to ask user's input until choice will be equal to 'a' OR 'd', but why I need to write && ? I don't get it.

do
{
    scanf("%c", &choice);
} while ( choice != 'a' && choice != 'd' );

I wanted to use ||, but it's not working.


Solution

  • There's nothing wrong with how the operators work, you need to get the logic for the code here.

    First, a do...while loop operates as long as the condition in the while is TRUE.

    In your case, you want to ask user's input until choice will be equal to 'a' OR 'd'.

    • So, in other way, as long as user input is not equal to a and d, you need to loop.

    • Logically, if the input is not equal to a, it can still be equal to d, so you have to check both the cases there. Only when, none of a or d is the input, you continue the loop.

    Remember, you're not checking the equality, you're checking the unequality. Only if both the inequalities are satisfied, then only the while condition evaluates to TRUE_ and you continue looping to ask for new value(s).

    In a nutshell, read DeMorgan's laws.