Why is this an issue?
Just because you can do something, doesn’t mean you should, and that’s the case with nested ternary operations. Nesting ternary operators
results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you)
scratching their heads and cursing.
Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement.
Noncompliant code example
int max(int p1, int p2, int p3) {
return p1 > p2 ? (p1 > p3 ? p1 : p3) : (p2 > p3 ? p2 : p3); // Noncompliant
}
Compliant solution
int max(int p1, int p2, int p3) {
if (p1 > p2) {
return p1 > p3 ? p1 : p3;
} else {
return p2 > p3 ? p2 : p3;
}
}
Exceptions
For C++11 mode only, the issue is not raised for ternary operators used inside constexpr
functions. In C++11 such functions are
limited to just a return statement, so the use of a ternary operator is required in them. This restriction is lifted in later standards, and thus
issues are raised.