Conditions
Quick Notes
Section titled “Quick Notes”Dùng if/else cho điều kiện linh hoạt.
Dùng switch khi so sánh một giá trị với nhiều case rời rạc.
C++17 hỗ trợ initializer trong if và switch để giới hạn scope biến tạm.
Syntax
Section titled “Syntax”if (score >= 90) { grade = 'A';} else { grade = 'B';}Example
Section titled “Example”int code = 2;
switch (code) {case 1: std::cout << "one\n"; break;case 2: std::cout << "two\n"; break;default: std::cout << "other\n";}Modern Switch
Section titled “Modern Switch”switch (int value = getValue(); value) {case 0: handleZero(); break;default: handle(value);}Common Mistakes
Section titled “Common Mistakes”- Quên
breaktrongswitchlàm rơi xuống case tiếp theo. - Viết điều kiện quá dài thay vì tách biến trung gian.
- Dùng assignment
=trong điều kiện khi muốn comparison==.
Search Keywords
Section titled “Search Keywords”conditions điều kiện if else switch switch initializer modern syntax