Skip to content

Commit 1aa68a3

Browse files
authored
[Edit] C: Switch (#7155)
* [Edit] C: Switch * Update switch.md ---------
1 parent a68b677 commit 1aa68a3

File tree

1 file changed

+61
-24
lines changed

1 file changed

+61
-24
lines changed

content/c/concepts/switch/switch.md

Lines changed: 61 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,67 @@
11
---
2-
Title: 'Switch' # Required; the file name should be the same as the title, but lowercase, with dashes instead of spaces, and all punctuation removed
3-
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)
4-
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!
2+
Title: 'Switch'
3+
Description: 'Provides a structure for supporting several options or conditions to execute a block of code.'
4+
Subjects:
55
- 'Code Foundations'
66
- 'Computer Science'
7-
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!
7+
Tags:
88
- 'Control Flow'
9-
- 'If'
109
- 'Else'
11-
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
10+
- 'If'
11+
- 'Switch'
12+
CatalogContent:
1213
- 'learn-c'
1314
- 'paths/computer-science'
1415
---
1516

16-
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.
17-
18-
However, it can only evaluate one expression or variable at a time.
17+
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.
1918

2019
## Syntax
2120

22-
```
21+
Here is the syntax for the `switch` statement (or the `switch` case):
22+
23+
```pseudo
2324
switch(expression) {
2425
case value1:
2526
// Enter code here
2627
break;
2728
case value2:
2829
// Enter code here
2930
break;
30-
case value_n:
31+
case valueN:
3132
// Enter code here
3233
break;
3334
default:
3435
// Enter code here
3536
}
3637
```
3738

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

40-
1. The switch `expression` is evaluated only once.
41-
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.
42-
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.
43-
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.
41+
Here's how the switch statement works:
4442

45-
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.
43+
1. The `expression` is evaluated only once.
44+
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.
45+
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.
46+
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.
4647

47-
## Example 1: Evaluating a variable
48+
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.
4849

49-
The following prints out some statements to a student based on a grade they got on a test or quiz.
50+
> **Note:** Remember that characters with type `char` are integral because they have integer ASCII codes.
51+
52+
## Switch vs If-Else
53+
54+
| **Feature** | **`switch` Statement** | **`if-else` Statement** |
55+
| -------------------- | ----------------------------------- | -------------------------------------------- |
56+
| Expression type | Works with `int`, `char`, `enum` | Supports all data types |
57+
| Readability | Cleaner for multiple values | Becomes lengthy with many conditions |
58+
| Execution Speed | Generally faster due to jump tables | Comparatively slower due to condition checks |
59+
| Range Checking | Not suitable for ranges | Suitable for conditions involving ranges |
60+
| Fall-Through Allowed | Yes (if `break` is omitted) | Not applicable |
61+
62+
## Example 1: Evaluating a Variable
63+
64+
This example prints out some statements to a student based on a grade they got on a test or quiz:
5065

5166
```c
5267
#include <stdio.h>
@@ -77,16 +92,16 @@ int main(){
7792
}
7893
```
7994

80-
This example will output:
95+
This code will output:
8196

8297
```shell
8398
Good job!
8499
Your grade is B
85100
```
86101

87-
## Example 2: Evaluating an expression
102+
## Example 2: Evaluating an Expression
88103

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

91106
```c
92107
#include <stdio.h>
@@ -109,10 +124,32 @@ int main(){
109124
}
110125
```
111126

112-
This example will output:
127+
This code will output:
113128

114129
```shell
115130
The addition of 1 and 3 results in 4
116131
```
117132

118-
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.
133+
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.
134+
135+
## Frequently Asked Questions
136+
137+
### 1. Can we use strings in `switch` cases?
138+
139+
No, C does not support `switch` with strings. It only works with `int`, `char`, and `enum` types.
140+
141+
### 2. What happens if we forget to add `break` in `switch`?
142+
143+
The control will _fall through_ to the next case and execute all subsequent cases until a `break` or end of `switch` is encountered.
144+
145+
### 3. Is `default` necessary in a `switch` statement?
146+
147+
No, `default` is optional in a `switch` statement. However, it is a good practice to include `default` to handle unexpected values.
148+
149+
### 4. Can two cases in `switch` have the same value?
150+
151+
No, case labels in `switch` must be unique. Duplicate case values will result in a compilation error.
152+
153+
### 5. Can we nest `switch` statements?
154+
155+
Yes, a `switch` can be nested inside another `switch`, though this can reduce code clarity and is rarely recommended.

0 commit comments

Comments
 (0)