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.

[Bonus Fact:]

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.

--

--

--

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Quiz | Computer Fundamentals | Set 21

After upgrading MacOS to Monterey, Firebase hosting no longer displays pages when accessing…

Python Tutorials for Absolute Beginners: Part 2

How to use story-points, velocity, and the cone of uncertainty to deliver in time

No Testing Strategy, No DevOps

Legacy Tools in Modern Stacks Part I: Make and Makefiles, Use Cases Beyond Compiling

Exception Handling in Java

Tutorial Fuzzy Logic Mamdani for Arduino

Tutorial Fuzzy Logic Mamdani for Arduino

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
Adam Reed

Adam Reed

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

More from Medium

Variables! — The building blocks of programming

Sharpness of C Sharp AKA C#

On the covariance, contravariance and invariance

PVS-Studio checks Umbraco code for the third time