Main Content

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

A pointer or reference parameter in a function shall be declared as pointer to const or reference to const if the corresponding object is not modified

Description

Rule Definition

A pointer or reference parameter in a function shall be declared as pointer to const or reference to const if the corresponding object is not modified.

Rationale

Best practice for function signature is to clearly communicate whether passing an object to the function by parameter results in a modification of the object. Consider these function signatures:

void foo(const in&);
void bar(int&);
Here, foo() accepts an integer as a const reference, which clearly communicates that the input reference is not modified by foo(). From the signature of bar(), it is not clear whether the input reference is modified or not.

To comply with this rule, const-qualify the type of named pointer or reference parameters. As an exception, this rule does not apply if a parameter is modified by any of the functions in a set of overriding functions.

Polyspace Implementation

The checker flags non-const pointer parameters if the underlying object is not modified in the function body.

If a pointer parameter is passed to another function as a non-const reference or pointer, the checker assumes that the parameter can be modified. Such parameters are not reported as violations.

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, the parameters *b and *c are not modified in the function and they are not qualified as const. Polyspace reports violations of this rule.

void sum(int *a, int *b, int *c, const int *d) { //Noncompliant 
	*a = *b + *c + *d;

}

Check Information

Group: Declarations
Category: Required

Version History

Introduced in R2018a

expand all