Main Content

AUTOSAR C++14 Rule A7-1-2

The constexpr specifier shall be used for values that can be determined at compile time

Since R2020b

Description

Rule Definition

The constexpr specifier shall be used for values that can be determined at compile time.

Rationale

If a variable value is computed from an expression that involves compile-time constants only, using constexpr before the variable definition, like this:

constexpr double eValSquared = 2.718*2.718;
ensures that the expression is evaluated at compile time. The compile-time evaluation saves on run-time overheads. Sometimes, the performance gains at run time can be significant.

If the expression cannot be evaluated at compile time, the constexpr keyword ensures that you get a compilation error. You can then fix the underlying issue if possible.

Note that the const keyword does not guarantee compile-time evaluation. The const keyword simply forbids direct modification of the variable value after initialization. Depending on how the variable is initialized, the initialization can happen at compile time or run time.

Polyspace Implementation

The checker flags a local variable definition without the constexpr specifier if the variable is initialized with one of the following and not modified subsequently in the code:

  • A compile-time constant, for instance, a literal value.

  • An expression involving compile-time constants only.

  • Calls to a function with compile-time constants as parameters, provided the function is itself constexpr or the function contains only a return statement involving its parameters.

  • A constructor call with a compile-time constant, provided all member functions of the class including the constructor are themselves constexpr.

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

double squareIfPositive(double val) {
    return val > 0? (val * val): 0;
}

constexpr double square(double val) {
    return val > 0? (val * val): 0;
}

void initialize(void) {
    double eVal = 2.718; //Noncompliant
    double eValSquare = squareIfPositive(2.718); //Noncompliant
    const double eValCubed = 2.718 * 2.718 * 2.718; //Noncompliant
    
    constexpr double eValSquareAnother = square(2.718); //Compliant
}

In this example, the first three variable definitions in the initialize function are noncompliant because the variables are initialized with expressions involving literal values and the constexpr keyword is omitted.

Check Information

Group: Declaration
Category: Required, Automated

Version History

Introduced in R2020b

expand all