- C language
- Basic grammar
- here
switch statement --fast conditional branching of integers
You can use a switch statement to perform fast conditional branching of integers.
switch (value) { case Case 1 value: // Process 1 break; case Case 2 value: // Process 2 break; case Case 3 value: // Process 3 break; default: default: // Processing in cases other than the above }
The break statement is not required, but if there is no break, the statement below is executed without moving outside the switch statement.
switch (value) { case Case 1 value: case Case 2 value: // Processing for case 1 or case 2 break; case Case 3 value: // Process 3 break; default: default: // Processing in cases other than the above }
Forgetting to write a break statement occurs frequently, empirically speaking. It seems that I forgot to write the break statement when I thought, "Oh, it's strange, the behavior of the program is too mysterious."
In the processing of each case of the switch statement, there are many cases where you want to declare variables, so if you want to declare variables, it is better to create a scope as follows.
switch (value) { case Case 1 value: { // Process 1 break; } case Case 2 value: { // Process 2 break; } case Case 3 value: { // Process 3 break; } default: { // Processing in cases other than the above } }
This is a sample using a switch statement. It is used in combination with enumeration type.
#include <stdint.h> #include <stdio.h> enum { SPVM_OP_C_ID_IF, SPVM_OP_C_ID_UNLESS, SPVM_OP_C_ID_ELSIF, SPVM_OP_C_ID_ELSE, SPVM_OP_C_ID_FOR, };; int main (void) { int32_t id = SPVM_OP_C_ID_UNLESS; switch (id) { case SPVM_OP_C_ID_IF: { printf("IF\n"); break; } case SPVM_OP_C_ID_UNLESS: { printf("UNLESS\n"); break; } case SPVM_OP_C_ID_ELSIF: { printf("ELSIF\n"); break; } case SPVM_OP_C_ID_ELSE: { printf("ELSE\n"); break; } case SPVM_OP_C_ID_FOR: { printf("FOR\n"); break; } default: { printf("No Match\n"); } } }
What is the internal implementation of the switch statement?
Imagine that two types of jump tables are selectively used by the integer pattern.
When the range of integers is small
The jump destination addresses are arranged at consecutive integer positions and can be jumped with the amount of calculation O (1).
5 0x1235 6 0x4568 7 NULL 8 NULL 9 0x3289
When the range of integers is large
The jump destination addresses are arranged in ascending order so that binary search is possible, and you can jump with the amount of calculation O (log n).
5 0x1237 6 0x4563 7000 0x8768 10000 0x3284
How do you use if and switch statements properly?
How do you use if statement and switch statement properly?
Use the switch statement only if it matches an integer. The switch statement works very well with enums.
Also, if there are many matches, it is faster than the if statement. For example, if you want to branch with 255 IDs, the switch statement is fast and suitable.