Main Content

AUTOSAR C++14 Rule A5-16-1

The ternary conditional operator shall not be used as a sub-expression

Description

Rule Definition

The ternary conditional operator shall not be used as a sub-expression.

Rationale

A ternary conditional operator used as a subexpression makes the full expression less readable and difficult to maintain. It is often visually clearer if you assign the result of a ternary operator to a variable and then use the variable in subsequent operations.

Polyspace Implementation

The checker flags uses of the ternary conditional operator in subexpressions with some exceptions. Exceptions include uses of the operator when:

  • The result is assigned to a variable.

  • The result is used as a function argument or returned from a function.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdint>
const int ULIM = 100000;

std::int32_t foo(int32_t x) {
    int ret;
    ret = (x <= 0? 0: (x >= ULIM? 0 : x)); //Noncompliant
    return ret;
}

std::int32_t bar(int32_t x) {
    int ret, retInterim;
    retInterim = x >= ULIM? 0 : x; //Compliant
    ret = retInterim <= 0? 0 : retInterim; //Compliant
    return ret;
}

In this example, in foo, a ternary conditional operation is chained with a second operation to return the value 0 if x is in the range [0, ULIM] and return x otherwise. The ternary operation comparing x with ULIM is a sub-expression in the full chain and violates the rule.

In bar, each ternary conditional operation is written in a separate step and does not violate the rule. Alternatively, the same algorithm can be implemented by combining the conditions with the boolean AND operator and using a single ternary conditional operation.

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019b