On an example I am working on, I have code to pick out the vowels between ‘a’ to ‘z’. It is using a switch statement that instead of separate cases, the character values are sharing the same case. From what I know so far, the expression involved i.e
***(letter * (letter >= 'a' && letter <= 'z'))***
evaluates to true or false and is converted to an integer (1 and 0) in which it falls through to “case 0:” (0 obviously being false) to deal with the result should it be false. Can anyone explain the expression to conversion process involved with this statement? particularly the reasoning behind the multiplication of the logical expression. Here is my example code:
char letter(0);
cout << endl
<< "Enter a small letter: ";
cin >> letter;
switch(letter * (letter >= 'a' && letter <= 'z'))
{
case 'a': case 'e': case 'i': case 'o': case 'u':
cout << endl << "You entered a vowel.";
break;
case 0:
cout << endl << "That is not a small letter.";
break;
default: cout << endl << "You entered a consonant.";
}
EDIT: All great answers guys. Cleared a lot up. Thanks again for your input
The conditional expression multiplicand will evaluate to a true or false. The ASCII value of
letterwill be compared to the characters “a” and “z”. True and false can be implicitly-converted to the numerals 1 and 0 respectively (andletterwill be converted to its numeric ASCII value). So it will either be:or
Anything times 0 is 0 which means without a corresponding case the control will go down to the default case (this one goes down to the
case: 0part). Otherwise,letter * (1)isletter, and therefore it will be compared by the other cases as if it wereswitch (letter).