How To Use A Switch Statement
Switch Statements are a super useful tool when you are wanting a nonstatic variable to determine various functions.
Now you could do this same thing using if statements like this:
But the more instances you add to this, the slower it is going to run. So if you wanted to do something like this but with better, faster performance then that’s where a switch statement comes in!
What makes up a switch statement?
Switch statements consist of 3 essential parts:
- Switch - Every switch statement must start with the word “switch” followed by parentheses “( )” that contains a variable of type (int, char, or enum).
- Case - These are the individual functions that run based on the various values assigned to the switch’s variable.
- Break - Each “case” must end with a “break” in order to let the switch statement know when to end each case.
Instead of using “case”, you can use “default” to call a function when the variable value doesn't match any of the other cases' values.