Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add "or" in switch statements?

People also ask

Can you use || in switch statements?

Answer 5562ce6c9113cb40db0002aaYou can't use “||” in case names. But you can use multiple case names without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a “break”.

Can I add or in switch-case?

The switch-case construct is pretty similar to an if-else statement, you can use the OR operator in an if however.

Can we use or operator in switch-case in C?

The logical OR operator (||) will not work in a switch case as one might think, only the first argument will be considered at execution time.

Can you use || IN case statement Ruby?

If you are eager to know how to use an OR condition in a Ruby switch case: So, in a case statement, a , is the equivalent of || in an if statement.


By stacking each switch case, you achieve the OR condition.

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7:
    case 12:
    ...
    break;
    ...
}

You do it by stacking case labels:

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7: 
    case 12:
    ...
    break;
    ...
}

case 2:
case 5:
do something
break;

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }


You may do this as of C# 9.0:

switch(myvar)
{
    case 2 or 5:
        // ...
        break;

    case 7 or 12:
        // ...
        break;
    // ...
}

The example for switch statement shows that you can't stack non-empty cases, but should use gotos:

// statements_switch.cs
using System;
class SwitchTest 
{
   public static void Main()  
   {
      Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); 
      Console.Write("Please enter your selection: "); 
      string s = Console.ReadLine(); 
      int n = int.Parse(s);
      int cost = 0;
      switch(n)       
      {         
         case 1:   
            cost += 25;
            break;                  
         case 2:            
            cost += 25;
            goto case 1;           
         case 3:            
            cost += 50;
            goto case 1;             
         default:            
            Console.WriteLine("Invalid selection. Please select 1, 2, or3.");            
            break;      
       }
       if (cost != 0)
          Console.WriteLine("Please insert {0} cents.", cost);
       Console.WriteLine("Thank you for your business.");
   }
}