โครงสร้างการตัดสินใจกำหนดให้โปรแกรมเมอร์ระบุเงื่อนไขอย่างน้อยหนึ่งเงื่อนไขที่จะประเมินหรือทดสอบโดยโปรแกรม พร้อมกับคำสั่งหรือคำสั่งที่จะดำเนินการหากเงื่อนไขถูกกำหนดให้เป็นจริง และทางเลือกอื่น ๆ ที่จะดำเนินการถ้าเงื่อนไข ถูกกำหนดให้เป็นเท็จ
ต่อไปนี้เป็นรูปแบบทั่วไปของโครงสร้างการตัดสินใจทั่วไปที่พบในภาษาโปรแกรมส่วนใหญ่ -

คำชี้แจงหากเป็นอย่างอื่น
คำสั่ง if สามารถตามด้วยคำสั่ง else ทางเลือก ซึ่งจะทำงานเมื่อนิพจน์บูลีนเป็นเท็จ ไวยากรณ์ของคำสั่ง if...else ใน C++ คือ −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
} else {
// statement(s) will execute if the boolean expression is false
} โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
} ผลลัพธ์
a is not less than 20; value of a is : 100
คำชี้แจงกรณีสลับกรณี
คำสั่ง switch ช่วยให้สามารถทดสอบตัวแปรเพื่อความเท่าเทียมกันกับรายการค่าต่างๆ แต่ละค่าจะเรียกว่า case และตัวแปรที่ถูกเปิดจะถูกตรวจสอบสำหรับแต่ละ case ไวยากรณ์สำหรับคำสั่ง switch ใน C++ มีดังต่อไปนี้ -
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
} โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
} ผลลัพธ์
You passed Your grade is D