Main Content

AUTOSAR C++14 Rule A7-1-1

Constexpr or const specifiers shall be used for immutable data declaration

Since R2020b

Description

Rule Definition

Constexpr or const specifiers shall be used for immutable data declaration.

Rationale

Declaring a variable const or constexpr reduces the chances that you modify the variable by accident. In addition, compilers can perform various optimizations on const and constexpr variables to improve run-time performance.

Polyspace Implementation

The checker flags:

  • Function parameters or local variables that are not const-qualified but never modified in the function body.

  • Pointers that are not const-qualified but point to the same location during its lifetime.

Function parameters of integer, float, enum, and Boolean types are not flagged.

If a variable is passed to another function by reference or pointers, the checker assumes that the variable can be modified. These variables are not flagged.

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 <cstddef>
bool Status;
extern int setStatus(); //sets Status; returns -1 if fails

char getNthChar(const char* str, int N){ //noncompliant
	int index=0;
	int status = setStatus(); //noncompliant
	while(*(str+index)!='\0'){
		if(index==N)
			return *(str+N);
		++index;
	}
		
	return '\0';
}
char getNthChar_const_safe(const char* const str, int N){
	int index=0;
	const int status = setStatus();
	while(*(str+index)!='\0'){
		if(index==N)
			return *(str+N);
		++index;
	}
		
	return '\0';
}

In the function getNthChar(), the C-string str is passed as a const char* parameter, meaning that the string *str is const. Because the pointer str does not change value, the pointer itself must be const qualified, as shown in the function getNthChar_const_safe. Polyspace flags the parameter str.

Because the local integer status is not modified in getNthChar(), it must be declared const, as shown in getNthChar_const_safe. Polyspace flags the declaration.

Check Information

Group: Declaration
Category: Required, Automated

Version History

Introduced in R2020b

expand all