Main Content

AUTOSAR C++14 Rule A8-4-8

Output parameters shall not be used

Since R2021a

Description

Rule Definition

Output parameters shall not be used.

Rationale

You can store the output value of a function in a variable that you pass to that function as a non-const reference or pointer parameter, for example:

void func(const T* input_var, T* output_var); //declaration
void func(const T* input_var, T* output_var)
{
    *output_var = *input_var % 2;
}

However, it is unclear from the function declaration whether the output parameter output_var passes a value to func and then stores the output (in-out parameter), or whether output_var only stores the output (out parameter). This might cause a developer to misuse the parameter, for instance by passing a null parameter when the function expects a non-null parameter.

Instead, use a return value to store the function output. The return value makes your intent clear and prevents possible misuse of the passed parameters, for example:

T* func(const T* input_var)
{
    return *input_var % 2;
}

Polyspace Implementation

Polyspace® flags all uses of non-const references or pointers in the parameter list of:

  • Functions, except for main().

  • Class constructors and operators.

If your code contains a function declaration and its definition, Polyspace flags the violation in the function definition.

Note

Polyspace flags a non-const reference or pointer in parameter lists even if that parameter is not used as an output parameter.

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>

std::int32_t func(const std::vector<int32_t>& inParam,
                  std::vector<int32_t>& outParam)  //  Non-Compliant
{
    //...
	return 1;
}

class C
{
public:

    C(C* ptr) {}         //  Non-Compliant
    C(C& ref) {}         //  Non-Compliant
    C(C&& rvalue_ref) {} //  Compliant
    C(const C& c) {}     //  Compliant
    C(const C&& c) {}    //  Compliant

    C& operator=(C& ref) { return *this; }    //    Non-Compliant

};

In this example, func has a return value of type std::int32_t but its parameter list is still non-compliant because it contains non-const lvalue reference outParam. Similarly, non-const parameters ptr and ref in the class constructors and in operator= are non-compliant.

Note that non-const parameter rvalue_ref is compliant because rvalue reference parameters bind only to temporary objects and these objects cannot be referenced after the function goes out of scope.

Check Information

Group: Declarators
Category: Required, Automated

Version History

Introduced in R2021a