简体   繁体   中英

Why doesnt the OR logical operator( || ) work?

I tried to use the OR logical operator in a do-while statement but for some reason it wouldn't work.

It would work with no OR logical operators(only with one statement) but otherwise no.

int main()
{
    char ansr;

    do
    {
        printf("What do you want to do?\n");
        printf("A = Add Employee\nR = Remove Employee\nE = Exit\n");
        scanf(" %c", &ansr);
    }while(ansr != 'E'||ansr != 'e');

    return 0;
}

Whenever i would write 'E' or 'e' I would expect the program to get out of the while loop but for some reason it would keep going through the do-while statement.

Logical OR (||) means "if either of these is true." In your case, if the input is not 'E' or it's not 'e' then it will perform another iteration. This is always true since even if it's one of them it's not going to be the other.

You're probably thinking of logical AND (&&):

while (ansr != 'E' && ansr != 'e');

This means "if both of these are true." If ansr is either 'E' or 'e', one of the clauses will be false, and the whole expression will then become false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM