Switch Statements to the Rescue

For a better readability

When we need to compare the value of a variable we can use the if statement. If there are several possibilities depending on the value of the variable then we would use if else if statement. This is fine if you are checking for 2 or maybe 3 outcomes, but what if you have many more, say 30 or 40 outcomes?

We have a better option for these cases, it is the switch statement.

I will first show you the if else if statement we actually have.

Now, lets turn this into a switch statement and you will see why it is better suited for these instances.

Switch statement

This does exactly the same thing as the previous code but this looks more organized, is easier to read, understand and write.

The switch(_powerupID) is letting the statement know what variable we are checking for.

Inside the brackets, we have the case statements. Each case is followed by the possible value _powerupID might have.

  • case 0:
  • case 1:
  • case 2:

Each case statement is closed with a colon (:)

Underneath each case statement is the code that will be run if the statement is true.

The powerup TripleShotPowerup is assigned the value of Powerup ID = 0. So it would check the first case test and if true, which it is, it will call the player.TripleShot() method.

The case statements must always end with a break; This is to tell the code to break out of the switch statement. If you don’t have the break statement, you will get an error uppon compilation.


At the end of all the case statements, we have a default: to capture any results outside the available possibilities. This also must end in a break.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store