Main Content

MISRA C++:2023 Rule 10.1.1

The target type of a pointer or lvalue reference parameter should be const-qualified appropriately

Since R2024b

Description

Rule Definition

The target type of a pointer or lvalue reference parameter should be const-qualified appropriately.

Rationale

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

void foo(const int& inparam);
void bar(int& i);
Here, foo() accepts an integer inparam as a const reference, which clearly communicates that foo() does not modify inparam. From the signature of bar(), it is not clear whether the function modifies inparam.

To comply with this rule, const-qualify the type of each named pointer or reference parameter, unless either of these condition is true:

  • The parameter is not an object type.

  • The parameter is assigned to a non-const pointer or reference in the function body.

  • The parameter is modified in the function body. Passing the parameter to a function as a non-const object modifies the parameter.

This rule does not apply to:

  • Unnamed parameters

  • Rvalue references

  • Parameters of virtual functions

  • Parameters of function templates

  • Parameters of functions or lambdas that are declared within the scope of a template

  • The main() function

Polyspace Implementation

The checker reports violations on non-const pointer or reference parameters if the underlying object is not modified in the function body.

If a pointer or reference 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;

}

In this example:

  • The parameter c of foo() is compliant because it is assigned to a non-const returned value.

  • The parameter array of getBegin() is not compliant because it is assigned to a const returned value.

  • This rule does not apply to the rvalue reference x and the unnamed float& parameter of the function foo().

auto &foo(int &&x, float &, char &c) { //Compliant
	return c;
}

auto getBegin(std::vector<int> &array) { //Noncompliant
	return array.cbegin();
}

Check Information

Group: Declarations
Category: Advisory

Version History

Introduced in R2024b