Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It Possible To Do The Following In A Switch Statement - C++?

I am a programming student in my second OOP class, and I have a simple question that I have not been able to find the answer to on the internet, if it's out there, I apologize.

My question is this:

Is it possible have Boolean conditions in switch statements?

Example:

switch(userInputtedInt)
{
    case >= someNum && <= someOtherNum
    break;
    // Is this possible?
}
like image 899
Alex Avatar asked Jan 19 '10 15:01

Alex


People also ask

What data types can be used in a switch statement C?

A switch works with the byte , short , char , and int primitive data types.

What do switch statements do in C?

A switch statement causes control to transfer to one labeled-statement in its statement body, depending on the value of expression . The values of expression and each constant-expression must have an integral type. A constant-expression must have an unambiguous constant integral value at compile time.

Can we use characters in switch-case in C?

Important points to C Switch Case Variables are not allowed inside the case label, but integer/character variables are allowed for switch expression. Break and default are optional.

Can we use a switch statement to switch on strings in C?

No you can't.


2 Answers

No this is not possible in C++. Switch statements only support integers and characters (they will be replaced by their ASCII values) for matches. If you need a complex boolean condition then you should use an if / else block

like image 176
JaredPar Avatar answered Oct 06 '22 13:10

JaredPar


As others have said you can't implement this directly as you are trying to do because C++ syntax doesn't allow it. But you can do this:

switch( userInputtedInt )
{
  // case 0-3 inclusve
  case 0 :
  case 1 :
  case 2 :
  case 3 :
    // do something for cases 0, 1, 2 & 3
    break;

  case 4 :
  case 5 :
    // do something for cases 4 & 5
    break;
}
like image 37
John Dibling Avatar answered Oct 06 '22 13:10

John Dibling