Main Content

MISRA C++:2008 Rule 7-1-1

A variable which is not modified shall be const qualified

Description

Rule Definition

A variable which is not modified shall be const qualified.

Rationale

Declaring a variable const reduces the chances that you modify the variable inadvertently.

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>

char getNthChar(const char* str, int N){//Noncompliant
	int index=0;
	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;

	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.

Check Information

Group: Declarations
Category: Required

Version History

Introduced in R2018a

expand all