5.8 Conditional operator

5.8.1 Do not use the conditional operator (?:) as a sub-expression

Evaluation of a complex condition is best achieved through explicit conditional statements (if/else). Using the result of the conditional operator as an operand reduces the maintainability of the code. The only permissible uses of a conditional expression are:

  • argument expression in a function call
  • return expression
  • initializer in a member initialization list
  • object initializer
  • the right hand side operand of assignment (excluding compound assignment)

The last use is allowed on the basis of initialization of an object with automatic storage duration being equivalent to its declaration, followed by assignment.

#include <cstdint>
               
void foo (int32_t i, int32_t j)
{
int32_t k;
k = (j != 0) ? 1 : 0;       // @@+ Compliant: equivalent to initialization +@@
               
// @@- Non-Compliant: nested conditional operations -@@
k = (i != 0) ? ((j != 0) ? 1 : 0) : 0;
                 
k = i + ((j != 0) ? 1 : 0); // @@- Non-Compliant -@@
}

References

  • HIC++ v3.3 – 10.20

Click here for references