break

Descrição

break é usado usado para sair de um laço for, while ou do...while, ignorando a condição padrão do loop. Também é usada para sair do comando switch case.

Código de Exemplo

Example with For Loop

Código de Exemplo 1

The following code exits the for loop when the i greater than 3

void setup() { Serial.begin(9600); Serial.println("====== TEST START ======"); for (int i = 1; i < 1000; i++) { Serial.print("Inside the FOR loop: i = "); Serial.println(i); if(i > 3) break; } Serial.println("====== TEST END ========"); } void loop() {}

The result on Serial Monitor:

COM6
Send
====== TEST START ====== Inside the FOR loop: i = 1 Inside the FOR loop: i = 2 Inside the FOR loop: i = 3 ====== TEST END ========
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Código de Exemplo 2

No códgo seguinte, o break quebra o loop for quando o valor do sensor excede o limiar.

int lim = 40; for (int x = 0; x < 255; x ++) { analogWrite(PWMpin, x); sens = analogRead(sensorPin); if (sens > lim) { // "foge" do o loop `for` x = 0; break; } delay(50); }

Example with While Loop

The following code exits the while loop when the i greater than 3

void setup() { Serial.begin(9600); Serial.println("====== TEST START ======"); int i = 0; while (true) { // while(true) means loop forever Serial.print("Inside the WHILE loop: i = "); Serial.println(i); if(i > 3) break; i++; // increase i by 1 } Serial.println("====== TEST END ========"); } void loop() { }

The result on Serial Monitor:

COM6
Send
====== TEST START ====== Inside the WHILE loop: i = 0 Inside the WHILE loop: i = 1 Inside the WHILE loop: i = 2 Inside the WHILE loop: i = 3 ====== TEST END ========
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Example with Do While Loop

The following code exits the while loop when the i greater than 3

void setup() { Serial.begin(9600); Serial.println("====== TEST START ======"); int i = 0; do { Serial.print("Inside the DO WHILE loop: i = "); Serial.println(i); if(i > 3) break; i++; // increase i by 1 } while (true); // while(true) means loop forever Serial.println("====== TEST END ========"); } void loop() { }

The result on Serial Monitor:

COM6
Send
====== TEST START ====== Inside the DO WHILE loop: i = 0 Inside the DO WHILE loop: i = 1 Inside the DO WHILE loop: i = 2 Inside the DO WHILE loop: i = 3 ====== TEST END ========
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Example with Switch Case

See example in switch...case

Ver Também

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.

※ OUR MESSAGES