Skip to content

[Edit] C: Switch #7155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 29, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 61 additions & 24 deletions content/c/concepts/switch/switch.md
Original file line number Diff line number Diff line change
@@ -1,52 +1,67 @@
---
Title: 'Switch' # Required; the file name should be the same as the title, but lowercase, with dashes instead of spaces, and all punctuation removed
Description: 'Evaluates several case conditions, and executes a code block if the case value is a match.' # Required; ideally under 150 characters and starts with a present-tense verb (used in search engine results and content previews)
Subjects: # Please only use Subjects in the subjects.md file (https://github.com/Codecademy/docs/blob/main/documentation/subjects.md). If that list feels insufficient, feel free to create a new Subject and add it to subjects.md in your PR!
Title: 'Switch'
Description: 'Provides a structure for supporting several options or conditions to execute a block of code.'
Subjects:
- 'Code Foundations'
- 'Computer Science'
Tags: # Please only use Tags in the tags.md file (https://github.com/Codecademy/docs/blob/main/documentation/tags.md). If that list feels insufficient, feel free to create a new Tag and add it to tags.md in your PR!
Tags:
- 'Control Flow'
- 'If'
- 'Else'
CatalogContent: # Please use course/path landing page slugs, rather than linking to individual content items. If listing multiple items, please put the most relevant one first
- 'If'
- 'Switch'
CatalogContent:
- 'learn-c'
- 'paths/computer-science'
---

In C, the **`switch case`** statement provides a structure for supporting several options or conditions to execute a block of code, similar to the `if..else-if..else` statement. A main difference here, though, is that this statement is much easier to read and write.

However, it can only evaluate one expression or variable at a time.
In C, the **`switch`** statement provides a structure for supporting several options or conditions to execute a block of code. It provides a clean and effective alternative to lengthy `if-else` chains when checking a [variable](https://www.codecademy.com/resources/docs/c/variables) against multiple constant values. It is commonly used when a given variable's value must be compared against multiple possible options.

## Syntax

```
Here is the syntax for the `switch` statement (or the `switch` case):

```pseudo
switch(expression) {
case value1:
// Enter code here
break;
case value2:
// Enter code here
break;
case value_n:
case valueN:
// Enter code here
break;
default:
// Enter code here
}
```

Here's how the switch (aka switch-case) statement works:
## How Switch Case Works

1. The switch `expression` is evaluated only once.
2. The value of the expression will be compared with the values of each `case`, and if there is a match the corresponding block of code is executed. If there is no code block provided in the `case`, the control moves on to the next `case` until it finds one with a code block, and executes the code block there.
3. The `break` keyword breaks out of the switch block, and does not evaluate any additional statements in the switch. (Without the `break`, execution would continue with the next `case` statement.) The program now exits the switch.
4. The code inside the `default` case is executed if none of the above cases are matched with the resulting value of the expression. This case is optional, and acts just like the `else` in an `if..else-if..else` statement. It serves as a "catch-all" case.
Here's how the switch statement works:

The expression or variable's resulting value must be of an integral or enumerated type. Examples of valid result types for switch-case expressions are `int`, `double`, `float`, and `char`. (Remember that characters, which have type `char`, are integral, because they have integer ASCII codes.) This statement will not be valid for expressions or variables that, for example, result in a string value.
1. The `expression` is evaluated only once.
2. The value of the expression will be compared with the values of each `case`, and if there is a match, the corresponding block of code is executed. If there is no code block provided in the `case`, the control moves on to the next `case` until it finds one with a code block, and executes the code block there.
3. The `break` keyword breaks out of the `switch` block, and does not evaluate any additional statements in the `switch`. Without the `break`, execution would continue with the next `case` statement.
4. The code inside the `default` case is executed if none of the above cases are matched with the resulting value of the expression. This case is optional, and acts just like the `else` in an `if-else` statement. It serves as a _catch-all_ case.

## Example 1: Evaluating a variable
The expression or variable's resulting value must be of an integral or [enumerated](https://www.codecademy.com/resources/docs/c/enums) type. Examples of valid result types for `switch` case expressions are `int`, `double`, `float`, and `char`. This statement will not be valid for expressions or variables that, for example, result in a string value.

The following prints out some statements to a student based on a grade they got on a test or quiz.
> **Note:** Remember that characters with type `char` are integral because they have integer ASCII codes.

## Switch vs If-Else

| **Feature** | **`switch` Statement** | **`if-else` Statement** |
| -------------------- | ----------------------------------- | -------------------------------------------- |
| Expression type | Works with `int`, `char`, `enum` | Supports all data types |
| Readability | Cleaner for multiple values | Becomes lengthy with many conditions |
| Execution Speed | Generally faster due to jump tables | Comparatively slower due to condition checks |
| Range Checking | Not suitable for ranges | Suitable for conditions involving ranges |
| Fall-Through Allowed | Yes (if `break` is omitted) | Not applicable |

## Example 1: Evaluating a Variable

This example prints out some statements to a student based on a grade they got on a test or quiz:

```c
#include <stdio.h>
Expand Down Expand Up @@ -77,16 +92,16 @@ int main(){
}
```

This example will output:
This code will output:

```shell
Good job!
Your grade is B
```

## Example 2: Evaluating an expression
## Example 2: Evaluating an Expression

The following determines if the addition of two numbers results in either a total of 5 or 4.
This example determines if the addition of two numbers results in either a total of `5` or `4`:

```c
#include <stdio.h>
Expand All @@ -109,10 +124,32 @@ int main(){
}
```

This example will output:
This code will output:

```shell
The addition of 1 and 3 results in 4
```

Just as aforementioned, a switch-case statement can be used to evaluate the value of not just a variable, but also an expression, as long as the expression results in one value that is either a number or something containing a numerical value.
Just as aforementioned, a `switch` statement can be used to evaluate the value of not just a variable, but also an expression, as long as the expression results in one value that is either a number or something containing a numerical value.

## Frequently Asked Questions

### 1. Can we use strings in `switch` cases?

No, C does not support `switch` with strings. It only works with `int`, `char`, and `enum` types.

### 2. What happens if we forget to add `break` in `switch`?

The control will _fall through_ to the next case and execute all subsequent cases until a `break` or end of `switch` is encountered.

### 3. Is `default` necessary in a `switch` statement?

No, `default` is optional in a `switch` statement. However, it is a good practice to include `default` to handle unexpected values.

### 4. Can two cases in `switch` have the same value?

No, case labels in `switch` must be unique. Duplicate case values will result in a compilation error.

### 5. Can we nest `switch` statements?

Yes, a `switch` can be nested inside another `switch`, though this can reduce code clarity and is rarely recommended.