Search code examples
c++switch-statementlogical-or

c++ switch - not evaluating and showing "Condition is always true"


I was experimenting whether I can use "logical or" inside case clause for a switch statement. I tried this way for the first case and the system skipped it all together when I gave input as "A" or "a" in both the cases.

# include <iostream>
using namespace std;

int main () {
  /* prg. checks if the input is an vowel */

  char ch;
  cout << "please input a word to check if it is vowel or not" << endl;
  cin >> ch;

  switch (ch) {
      case ('A'|| 'a') :
          cout << "it is vowel" << endl;
          break;

      case 'E':
          cout << "it is vowel" << endl;
          break;

      case 'I':
          cout << "it is vowel" << endl;
          break;

      case 'O':
          cout << "it is vowel" << endl;
          break;

      case 'U':
          cout << "it is vowel" << endl;
          break;

      default:
          cout << "it is not a vowel" << endl;
          break;


  }

is there a proper way to use or inside the case clause ?

Thank you for the help.


Solution

  • The case ('A'|| 'a') should be written as:

    switch (ch) {
    case 'A':
    case 'a':
        cout << "it is vowel" << endl;
        break;
    // ...
    

    If it matches on 'A' it will fall through to the next case (unless there's a break in between).

    In this case, you may want to combine all vowles:

    switch (ch) {
    case 'A':
    case 'a':
    case 'E':
    case 'e':
    //... all of them ...
        std::cout << "it is vowel\n";
        break;
    // ...
    

    Note that some compilers will issue a warning for fall through cases with statements in them (which is not the case above). Since C++17, if you use fall through cases, you can use the fallthrough attribute to silence such warnings where you actually want a fall through.