Jump to content

Clever use for switch loop


esmith

Recommended Posts

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";
}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...