Can somebody explain why the do…while loop is repeating itself in for b, B, c, or C but not if you put a or A? This is a subpart of the code I am writing up. I want to limit the number of input to only a, b, or c so that any other input just repeats itself until it gets one of the correct letters.
do{
printf("Which package would you like to select? A, B, or C ");
scanf(" %c", &package_choice);
}while(toupper((unsigned char)package_choice) != 'A' && 'B' && 'C');
I have changed the && to || but it repeats itself over and over no matter the input. I went through and did the (unsigned char)package_choice) != to each letter to see if that changed anything but I got the same result. I’m still learning C in school and am having a hard time understanding some of the basic formats that go along with C. Thank you for any help!
>Solution :
This line is not doing what you think it does:
while(toupper((unsigned char)package_choice) != 'A' && 'B' && 'C');
… what the above actually does is logically equivalent to this:
while(toupper((unsigned char)package_choice) != 'A' && ('B' != 0) && ('C' != 0));
… and since ‘B’ (aka ASCII value 66) and ‘C’ (aka ASCII value 67) are always not equal to zero, those parts of the expression will always trivially evaluate to true and therefore have no effect on the behavior of the test.
Rewritten to properly express the logic you intended, the expression should look like this:
while(toupper((unsigned char)package_choice) != 'A'
&& toupper((unsigned char)package_choice) != 'B'
&& toupper((unsigned char)package_choice) != 'C');