break
break 는 for, while 또는 do...while loop 로부터 빠져나가 정상 루프를 건너 뛰는데 쓰인다. switch case 문으로부터 빠져나갈 때도 쓰인다.
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() {}
시리얼 모니터에 결과:
====== TEST START ======
Inside the FOR loop: i = 1
Inside the FOR loop: i = 2
Inside the FOR loop: i = 3
====== TEST END ========
아래 코드에서, 센서값이 임계값을 넘을 때 제어는 for 를 빠져나간다.
int threshold = 40;
for (x = 0; x < 255; x++) {
analogWrite(PWMpin, x);
sens = analogRead(sensorPin);
if (sens > threshold) {
x = 0;
break;
}
delay(50);
}
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) {
Serial.print("Inside the WHILE loop: i = ");
Serial.println(i);
if(i > 3)
break;
i++;
}
Serial.println("====== TEST END ========");
}
void loop() {
}
시리얼 모니터에 결과:
====== 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 ========
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++;
} while (true);
Serial.println("====== TEST END ========");
}
void loop() {
}
시리얼 모니터에 결과:
====== 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 ========
See example in switch...case
※ ARDUINO BUY RECOMMENDATION
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.