Nested ternaries are hard to read and can make the order of operations complex to understand.
int max(int p1, int p2, int p3) {
return p1 > p2 ? (p1 > p3 ? p1 : p3) : (p2 > p3 ? p2 : p3); // Noncompliant
}
Instead, use another line to express the nested operation in a separate statement.
int max(int p1, int p2, int p3) {
if (p1 > p2) {
return p1 > p3 ? p1 : p3;
} else {
return p2 > p3 ? p2 : p3;
}
}
Exceptions
In C++11, the rule ignores ternary operators inside constexpr
functions.
Indeed, in C++11, such functions are limited to just a return statement, so using a ternary operator might be required. Later standards lifted this
restriction, so this exception does not apply to them.
constexpr int max(int p1, int p2, int p3) {
return p1 > p2 ? (p1 > p3 ? p1 : p3) : (p2 > p3 ? p2 : p3); // Compliant by exception in C++11
}