Jump to content
Returning Members: Password Reset Required ×

How to Use a Switch/Case Conditional Structure


Recommended Posts

Posted

This is my first topic is a way to say hi.

Since I plan to spend a lot of time here, let's get to the basics.

In a way to reduce complexity, I've seen some structures using multiple handlers in a single file class.

To make this clearer, let's look at the syntax of switch/case:

switch (variable or value)
{
case value1:
     // code 1
break;
case value2:
     // code 2
break;
}

In line 1, under switch (variable or value), we define the variable or value we want to compare. In line 3, we inform that if the value declared in this case is equal to the one contained in the switch, code 1 will be executed. The same behavior applies to the second case. Furthermore, if the value contained in the switch is not met in one of the conditions, no block will be executed.

And the break command? The break command is used to specify the last line of code to be executed within the condition. If not declared, codes implemented within subsequent cases will be executed.

If you want to run the same code for different values, you can program the switch/case as follows:

switch (variable or value)
{
         case value1:
         case value2:
         case value3:
                   // code 1
                   break;
         case value4:
         case value5:
         case value6:
                   // code 2
                   break;

In this case, we declare two blocks of code. The first (code 1) will be executed if the switch value is equal to value1, value2 or value3; and the second (code 2), if the value is equal to value4, value5 or value6.

Correct me if I'm wrong.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  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...