Main Content

AUTOSAR C++14 Rule A8-5-3

A variable of type auto shall not be initialized using {} or ={} braced-initialization

Since R2020a

Description

Rule Definition

A variable of type auto shall not be initialized using {} or ={} braced-initialization.

Rationale

Type deduction for auto has a counter-intuitive result when the initialization uses braces. The deduced type is std::initializer_list<> instead of the type that you might guess from the initializer.

For instance, the definition:

auto x{1};
results in the type of x being std::initializer_list<int> instead of int. Some compilers deduce an int type from this definition, but the behavior is not uniform across compilers.

Polyspace Implementation

The checker flags variable definitions that use the type auto if the variable is initialized using the {} or ={} braced initialization.

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<initializer_list>

void func() {
    auto aVar{1}; //Noncompliant
    auto anotherVar(1); //Compliant
    int aThirdVar{1}; //Compliant
    
    auto aVarList{1,2,3}; //Noncompliant
    std::initializer_list<int> anotherVarList{1,2,3}; //Compliant
}

In this example, the rule is violated when the auto type is used with braced initialization. Instead of auto, an explicit type specification is preferred. Alternatively, the initialization can use parenthesis (), which ensures the expected type deduction.

Check Information

Group: Declarators
Category: Required, Automated

Version History

Introduced in R2020a