PDA

View Full Version : Clever use for switch loop


esmith
June 20th, 2013, 09:16 AM
While researching a solution for another thread, I came across a clever use of the switch statement. Often I wish I could set up cases that use conditionals rather than a specific value. In the past, I used multiple else/if statements, but now I can do this:

switch (true) {
case counter<=8:
table = "Table 1";
break;
case counter<=16:
table = "Table 2";
break;
case counter<=24:
table = "Table 3";
break;
case counter<=32:
table = "Table 4";
break;
case counter<=40:
table = "Table 5";
break;
case counter<=48:
table = "Table 6";
break;
case counter<=56:
table = "Table 7";
break;
case counter<=64:
table = "Table 8";
break;
case counter<=72:
table = "Table 9";
break;
case counter<=80:
table = "Table 10";
break;
case counter<=88:
table = "Table 11";
break;
case counter<=96:
table = "Table 12";
break;
case counter<=104:
table = "Table 13";
break;
default:
table = "Table 14";
}

Dan Korn
June 20th, 2013, 09:55 AM
That is clever, but this works also:
table = "Table " + Int((counter - 1) / 8) + 1;:cool:

esmith
June 20th, 2013, 10:38 AM
Touche. Perhaps my use case is a bad example. But testing for "TRUE" in a switch loop seems to open up several possibilities that may not always have a math one liner. :P

Dan Korn
June 20th, 2013, 01:05 PM
Touche. Perhaps my use case is a bad example. But testing for "TRUE" in a switch loop seems to open up several possibilities that may not always have a math one liner. :P
Yes, absolutely. I've used that before as well:
http://forums.pti.com/showpost.php?p=1157&postcount=4

But, as that post shows, there's almost always a more succinct way to structure the code to isolate the actual comparisons.