switch...case
Beschreibung
Wie auch if-Statements, erlaubt es auch switch case, dass abhängig von der Bedingung in verschiedenen Situationen unterschiedlicher Code ausgeführt wird. Im Detail vergleicht switch case die Variablenwerte mit denen in den case-Statements. Wenn ein passendes case-Statement gefunden wird, so wird der Code in diesem case-Statement ausgeführt.
Das break-Keywort beendet das switch case-Statement und wird üblicherweise am Ende jedes case-Statements verwendet. Wenn kein break-Keywort verwendet wird, führt switch case alle Statements aus, bis ein break-Keywort auftaucht oder das switch case zu Ende ist.
Syntax
Parameter
- var: Eine Variable, die mit den eizelnen Fällen verglichen werden sollen. Erlaubte Datentypen: int, char.
- label1, label2: Konstanten. Erlaubte Datentypen: int, char.
Rückgabewert
Nichts.
Beispielcode
Das ergebnis am seriellen monitor:
※ Anmerkungen und Warnungen:
if we does not use the break in a case, the next case will also be executed. The execution is stopped when it reaches a break. Let's comment or remove a break in the above example and see the result.
Das ergebnis am seriellen monitor:
As you can see, when i = 1, the code run through case 1 and case 2.
Advanced Usage
If we miss a break in a case by accident, it results in the wrong operation of the code. Why the language does not force to use break instead of optional? Let's see two advanced usages to know the reason why.
Advanced Usage 1
Let's see the below example:
Das ergebnis am seriellen monitor:
In the above code, you can see the case 1, 2 and 3 have the same code (do the same work). Let's remove all code in the case 1 and case 2:
Das ergebnis am seriellen monitor:
As you can see, the results of both example codes are the same. But the second example code are shorter. Furthermore, if you get familiar to the second example code, you will realize that the second code is more readable. That is the benefit of not using the break;
Advanced Usage 2
Let's see the below example:
Das ergebnis am seriellen monitor:
In the above code, you can see the case 1 and 2 have the same a line of code (Serial.println("Arduino")). Let's compare with the below code:
Das ergebnis am seriellen monitor:
As you can see, the results of both example codes are the same. However, the second example code are shorter. That is another benefit of not using the break;
Siehe Auch
※ ARDUINO KAUFEMPFEHLUNG
Arduino UNO R3 | |
Arduino Starter Kit |