C++ อื่น ๆ ถ้า
อย่างอื่นถ้างบ
ใช้else if
คำสั่งเพื่อระบุเงื่อนไขใหม่หากเงื่อนไขแรกfalse
คือ
ไวยากรณ์
if (condition1) {
// block of code to be executed if
condition1 is true
} else if (condition2) {
// block of
code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false
and condition2 is false
}
ตัวอย่าง
int time = 22;
if (time < 10) {
cout << "Good
morning.";
} else if (time < 20) {
cout << "Good
day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
ตัวอย่างอธิบาย
ในตัวอย่างข้างต้น เวลา (22) มากกว่า 10 ดังนั้นเงื่อนไขแรกคือ false
เงื่อนไขต่อไปใน
else if
คำสั่งก็คือ เช่นfalse
กัน ดังนั้นเราจึงย้ายไปยังelse
เงื่อนไข เนื่องจากเงื่อนไขที่ 1 และเงื่อนไขที่ 2 เป็นทั้งfalse
- และพิมพ์ไปที่หน้าจอ "สวัสดีตอนเย็น"
แต่ถ้าเป็นเวลา 14 ปี โปรแกรมของเราจะพิมพ์คำว่า "Good day"