break

Description

L'instruction break est utilisée pour sortir d'une boucle do, for ou while, en passant outre le déroulement normal de la boucle. Cette instruction est également utilisée pour sortir d'une instruction switch.

Syntaxe

break;

Exemple

Example with For Loop

Exemple 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  

Exemple 2

for (x = 0; x < 255; x ++) // boucle for comptant x de 0 à 255 { // mettre une impulsion de largeur x sur la broche digitalWrite(PWMpin, x); // lire la valeur de la tension d'un capteur sur la broche sens = analogRead(sensorPin); // si la mesure est supérieure à un seuil, on sort de la boucle if (sens > threshold){ x = 0; break; // sortie de la boucle } delay(50); // pause de 50ms }

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

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES