Main Content

AUTOSAR C++14 Rule A5-1-6

Return type of a non-void return type lambda expression should be explicitly specified

Since R2020b

Description

Rule Definition

Return type of a non-void return type lambda expression should be explicitly specified.

Rationale

A compiler can deduce the return type of a lambda expression based on the type of the return expression. For instance, if a lambda expression does not return anything, the compiler deduces that the return type is void.

Specifying a return type when you declare a lambda expression is optional. For non-void return type lambda expressions, if you do not specify a return type explicitly, a developer reading your code might be confused about which type the lambda expression returns.

An explicit return type also reinforces type checking when the compiler generates an implicit conversion from the type of the returned expression to the expected return type.

Polyspace Implementation

Polyspace® flags lambda expressions with non-void-return types if the return type is not specified explicitly.

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<iostream>
#include <cstdint>
#include <cstdio>

void  func()
{
    std::uint8_t TARGET = 10;
    auto lambda_incr = [&](std::uint8_t x) -> std::uint8_t {//Compliant
        while (x < TARGET)
            x++;
        return x;

    };
    auto lambda_decr = [&](std::uint8_t y) { //Non-compliant, returned type is not specified
        while (y > TARGET)
            y--;
        return y;

    };
    char exp[] = "hello.";
    auto lambda3 = [exp]() { //Compliant, void return type.
        std::cout << exp << std::endl;
    };

    auto x = lambda_incr(5);
    auto y = lambda_decr(11);
    lambda3();


}

In this example, Polyspace flags lambda expression lambda_decr because no return type is specified. Polyspace does not flag lambda3 even though no return type is specified because the expression does not return anything (void return type).

Check Information

Group: Expressions
Category: Advisory, Automated

Version History

Introduced in R2020b