How to write switch statement with "or" logic?

user2152739 picture user2152739 · Mar 10, 2013 · Viewed 11.1k times · Source

Below, I have created a simple switch statement that works fine. I was wondering how I could change this code so it is switch(c), then case 1, case 2, case 3, default.

Example: if char is 'w' || char is 'W' return WHITE

I tried a simple if statement and it wasn't giving me the correct output despite it compiling successfully. Hope you can help. Thanks! :)

static COLORS color(char c) {

    switch(toupper(c)) {

        case 'W' : return WHITE;

        case 'B' : return BLUE;

        case 'R' : return RED;

        default  : return DEFAULT;
    }
}

Answer

Aiias picture Aiias · Mar 10, 2013

You can simply bunch together multiple cases:

switch (c) {
  case 'w':
  case 'W':
    // Code
    break;
  default:
    // Code
}

See MSDN switch() documentation.