Main Content

MISRA C++:2023 Rule 11.3.1

Variables of array type should not be declared

Since R2024b

Description

Rule Definition

Variables of array type should not be declared.

Rationale

The size information of C-style array objects is not always preserved. It is safer to use containers such as std::array that preserve the size information.

As an exception, declaring a const char array is not a violation if the array is immediately initialized with a string literal.

Polyspace Implementation

Polyspace® reports a violation of this rule if your code contains a C-style array. Polyspace does not report a violation of this rule when passing a traditional C-style array to a function because arrays decay to pointers when passed to a function as an argument.

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

In this example, a C-style array of integers numbers is declared in the function foo(). The size of this array is not immediately known. The function sum() checks the bounds of the passed array numbers by using a second parameter size. Because the size information of numbers is not preserved, sum() cannot validate whether size represents the length of numbers. Polyspace reports a violation of this rule.

int sum(const int *numbers, size_t size);

void foo() {
	int numbers[] = { 1, 2, 3, 4, 5 };//Noncompliant
	size_t size = sizeof(numbers) / sizeof(numbers[0]);

	int totalSum = sum(numbers, size);
	//...
}

Check Information

Group: Declarators
Category: Advisory

Version History

Introduced in R2024b