Ternary expressions, while concise, can often lead to code that is difficult to read and understand, especially when they are nested or complex.
Prioritizing readability fosters maintainability and reduces the likelihood of bugs. Therefore, they should be removed in favor of more explicit
control structures, such as if
/else
statements, to improve the clarity and readability of the code.
Code examples
Noncompliant code example
printf("%s", (i > 10 ? "yes" : "no")); // Noncompliant
Compliant solution
if (i > 10) {
printf("yes");
} else {
printf("no");
}
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.