You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/c/concepts/switch/switch.md
+61-24Lines changed: 61 additions & 24 deletions
Original file line number
Diff line number
Diff line change
@@ -1,52 +1,67 @@
1
1
---
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:
5
5
- 'Code Foundations'
6
6
- '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:
8
8
- 'Control Flow'
9
-
- 'If'
10
9
- '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:
12
13
- 'learn-c'
13
14
- 'paths/computer-science'
14
15
---
15
16
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.
19
18
20
19
## Syntax
21
20
22
-
```
21
+
Here is the syntax for the `switch` statement (or the `switch` case):
22
+
23
+
```pseudo
23
24
switch(expression) {
24
25
case value1:
25
26
// Enter code here
26
27
break;
27
28
case value2:
28
29
// Enter code here
29
30
break;
30
-
case value_n:
31
+
case valueN:
31
32
// Enter code here
32
33
break;
33
34
default:
34
35
// Enter code here
35
36
}
36
37
```
37
38
38
-
Here's how the switch (aka switch-case) statement works:
39
+
## How Switch Case Works
39
40
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:
44
42
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.
46
47
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.
48
49
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.
| 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:
50
65
51
66
```c
52
67
#include<stdio.h>
@@ -77,16 +92,16 @@ int main(){
77
92
}
78
93
```
79
94
80
-
This example will output:
95
+
This code will output:
81
96
82
97
```shell
83
98
Good job!
84
99
Your grade is B
85
100
```
86
101
87
-
## Example 2: Evaluating an expression
102
+
## Example 2: Evaluating an Expression
88
103
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`:
90
105
91
106
```c
92
107
#include<stdio.h>
@@ -109,10 +124,32 @@ int main(){
109
124
}
110
125
```
111
126
112
-
This example will output:
127
+
This code will output:
113
128
114
129
```shell
115
130
The addition of 1 and 3 results in 4
116
131
```
117
132
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