Main Content

AUTOSAR C++14 Rule M5-2-12

An identifier with array type passed as a function argument shall not decay to a pointer

Description

Rule Definition

An identifier with array type passed as a function argument shall not decay to a pointer.

Rationale

When you pass an array to a function as a pointer, the size information of the array becomes lost. Losing information about the array size might lead to confusion and unexpected behavior.

Avoid passing arrays as pointers to function. To pass arrays into a function, encapsulate the array into a class object and pass the object to functions. Starting in C++11, the standard template library implements several container classes that can be used to pass an array to a function. C++20 has the class std::span, which preserves the size information.

Polyspace Implementation

Polyspace® raises a violation when you use an array in a function interface.

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

void f1( int p[ 10 ] ); // Noncompliant

void f2( int ( &p )[ 10 ] );// Compliant 
void foo ()
{
int a[ 10 ];
f1( a );

f2( a ); 
}

In this example,the interface of f1() uses an array. When you pass the array a[10] to f1() as a pointer, the size of the array a is lost. Polyspace flags the declaration of f1(). If you pass arrays to function while preserving the dimensionality information, as shown by f2(), Polyspace does not raise a violation.

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019a