switch...case
Descrição
Da mesma forma que o comando if, o comando switch case controla o fluxo do programa permitindo ao programador especificar código diferente para ser executado em várias condições. Em particular, um comando switch compara o valor de uma variável aos valores especificados nos comandos case. Quando um comando case é encontrado cujo valor é igual ao da variável, o código para esse comando case é executado.
A palavra-chave break interrompe o comando switch, e é tipicamente usada no final de cada case. Sem um comando break, o comando switch irá continuar a executar as expressões seguintes (desnecessariamente) até encontrar um break, ou até o final do comando switch ser alcançado.
Sintaxe
Parâmetros
- var: uma variável para ser comparada com os vários cases. Tipos de dados permitidos: int, char
- valor1, valor2: constantes. Tipos de dados permitidos: int, char
Retorna
Nada
Código de Exemplo
The result on Serial Monitor:
※ Notas e Advertências:
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.
The result on Serial 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:
The result on Serial 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:
The result on Serial 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:
The result on Serial 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:
The result on Serial 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;
Ver Também
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |