SWITCH STATEMENTS
PUBLISHED 9/26/2023
Last updated
PUBLISHED 9/26/2023
Last updated
Power Up System --> Create a simple switch statement to compare the value of a variable against the value of a collected power up to activate the correct ability.
Enemy Types --> Create a simple switch statement to compare the enemy type and run the correct code to activate that enemies behavior
Weapon Types --> Create a simple switch statement to compare the player's weapon and execute the proper code accordingly
A switch statement allows a program to filter through a list of possible options, or cases, based on the value of a certain expression. --> Useful when you have limited number of options and you want to perform a different action for each one
Expression is the variable being evaluated and it's value is compared against each value stored in each case.
Each Case holds a value that will be compared against the Expression's value. Each case should also hold some sort of function that should be ran if the expression's value matches the case's value.
There is also an optional option to include a Default Case which allows the program to run functions if the Expression's value does not match any of the Case's value.
The Break statement is IMPORTANT! It is used to exit the switch statement once the necessary functions are ran and prevents the code from executing through the other cases.
Switch statements and if-else statements are both Control Flow Statements that allow you to execute different code depending on certain conditions.
Use switch statements over if-else statements when:
The program has a limited number of options and needs to perform a different action for each one
The program only has one option that can be true at a time
the program is based on a single expression/variable rather than multiple expressions/variables
Use an if-else statement over a switch statement when the program has a complex set of conditions that cannot be easily expressed in a switch statement