if (i > 4) {
// Do sth
} else if (i > 2) {
// Do sth else
} else { // Do sth else }
Format
if (<initializer>; <conditional_expression>) {
<if_body>
} else if (<else_if_expression>){
<else_if_body>
} else { <else_body>}
Example
if (Employee employee { getEmployee() }; employee.salary > 1000) { ... }
cout << ((i > 2) ? "yes" : "no");| Operator | Description | Usage |
|---|---|---|
<, <=, >, >= | Relational comparisons (same as math) | if (i < 0) { … } |
== | Equality | if (i == 3) { … } |
!= | Inequality | if (i != 3) { … } |
<=> | Three-way comparison (spaceship) | auto r = i <=> 0; |
! | Logical NOT | if (!flag) { … } |
&& | Logical AND | if (a && b) { … } |
\|\| | Logical OR | if (a \|\| b) { … } |
bool result { bool1 || bool2 || (i > 7) || (27 / 13 % i + 1) < 2 }; bool1 is true, rest is not checked <<=> (spaceship operator): can tell whether value is equal, less than or greater than another value<compare> and in the std namespacestd::strong_ordering (for integrals operand), std::weak_ordering (for custom-defined types), or std::partial_ordering (for floating-point types) (example 1)<compare> header, there's predicates s.t. we don't have to write strong_ordering::less every time (example 2)int i { 11 };
strong_ordering result { i <=> 0 };
if (result == strong_ordering::less) {
cout << "less" << endl; }
if (result == strong_ordering::greater) {
cout << "greater" << endl; }
if (result == strong_ordering::equal) {
cout << "equal" << endl; }
Example 2
#include <compare>
using namespace std;
int main() {
int i{11};
// 1) Use the spaceship operator; it yields a strong_ordering
strong_ordering result = (i <=> 0);
// 2) Interpret that ordering with the helper functions:
if (is_lt(result)) cout << "i is less than 0\n";
if (is_eq(result)) cout << "i is equal to 0\n";
if (is_gt(result)) cout << "i is greater than 0\n";
return 0;
}
switch (<initializer>; <expression>) { <body> }case expression even though it's been caught at some pointStandard and Default even though if it gets caught in Standardbreak not implemented correctly. Compiler will usually issue warning, but if this is intentional, use [[fallthrough]] to tell compiler this is intentional (example 2)Example 1
enum class Mode { Default, Custom, Standard };
int main() {
int value { 42 };
Mode mode { /* ... */ };
switch (mode) {
using enum Mode; // Allows direct use of enum values without qualification
case Custom:
value = 84;
break; // Added break to prevent fallthrough
case Standard:
case Default:
// Do something with value
std::cout << "Value: " << value << std::endl;
break;
}
return 0;
}
Example 2
switch (mode) {
using enum Mode; // Allows direct use of enum values without qualification
case Custom:
value = 84;
[[fallthrough]];
case Standard:
case Default:
// Do something with value
std::cout << "Value: " << value << std::endl;
break;
}