Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use greater than or equal in a switch statement

Tags:

What is the best way to check if variable is bigger than some number using switch statement? Or you reccomend to use if-else? I found such an example:

int i;  if(var1>var2) i = 1; if(var1=var2 i = 0; if(var1<var2) i = -1;  switch (i); {     case -1:     do stuff;     break;      case 0:     do stuff;     break;      case 1:     do stuff;     break;  } 

What can you tell a novice about using "greater than or equal" in switch statements?

like image 433
Vlad Holubiev Avatar asked Aug 29 '13 11:08

Vlad Holubiev


People also ask

Can you use greater than in switch?

SWITCH versus IFS However, SWITCH is limited to exact matching. It is not possible to use operators like greater than (>) or less than (<) with the standard syntax.

Can you do a comparison in a switch statement?

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String. equals method; consequently, the comparison of String objects in switch statements is case sensitive.

Does switch case use == or ===?

The switch statement uses the strict comparison ( === ). Third, execute the statement in the case branch where the result of the expression equals the value that follows the case keyword. The break statement exits the switch statement.

Can I use || with switch cases?

You can't use “||” in case names.


2 Answers

Not sure if this is what you're asking, but you could do it this way:

int var1; int var2;  int signum = Long.signum((long)var1 - var2); switch(signum) {     case -1: break;     case 0: break;     case 1: break; } 
like image 152
Stewart Avatar answered Nov 07 '22 19:11

Stewart


I would strongly recommend a if(var1>var2){}else if (var1==var2) {} else {} construct. Using a switch here will hide the intent. And what if a break is removed by error?

Switch is useful and clear for enumerated values, not for comparisons.

like image 29
Guillaume Avatar answered Nov 07 '22 20:11

Guillaume