if...else 는 코드의 흐름위에 기본 if 보다 큰 제어를 허용하는데, 그룹으로 다중 테스트할 수 있기 때문. else 는(존재하면) if 문의 결과가 false 일 때 실행될 거다. else 는 또다른 if 테스트를 진행할 수 있으므로, 다중, 서로 독립된 테스트가 같은 시간에 돌아갈 수 있다.
각 테스트는 참 테스트를 만날 때까지 다음 테스트를 진행한다. 참 테스트를 발견하면, 코드 블록을 돌리고, 프로그램은 다음 전체 if/else 구성을 건너뛴다. 참으로 입증된 테스트가 없으면, 기본 else 블록이 실행되며, 기본 동작이 설정된다.
elseif 블록이 else 블록을 가지거나 가지지 않을 수 있으며 그 반대도 됨을 주의하세요. 이러한 elseif 가 무제한 허용된다.
문법
if (condition1) {// do Thing A}elseif (condition2) {// do Thing B}else {// do Thing C}
예제 코드
예제 코드 1
The below code deternine numbers are odd or even
int i = 0;voidsetup() {Serial.begin(9600);}voidloop() {if ((i % 2) == 0) {Serial.print("Inside the IF statement: i = ");Serial.print(i);Serial.println(", even number"); } else {Serial.print("Inside the IF statement: i = ");Serial.print(i);Serial.println(", odd number"); } i++; // increase i by 1delay(500);}
시리얼 모니터에 결과:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
Inside the IF statement: i = 0, even number
Inside the IF statement: i = 1, odd number
Inside the IF statement: i = 2, even number
Inside the IF statement: i = 3, odd number
Inside the IF statement: i = 4, even number
Inside the IF statement: i = 5, odd number
Inside the IF statement: i = 6, even number
Inside the IF statement: i = 7, odd number
Ln 11, Col 1
Arduino Uno on COM15
2
예제 코드 2
아래는 온도 센서 코드에서 뽑았다
if (temperature >= 70) {//Danger! Shut down the system}elseif (temperature >= 60 && temperature < 70) {//Warning! User attention required}else {//Safe! Continue usual tasks...}
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 .