Main Content

AUTOSAR C++14 Rule A5-2-3

A cast shall not remove any const or volatile qualification from the type of a pointer or reference

Description

Rule Definition

A cast shall not remove any const or volatile qualification from the type of a pointer or reference.

Rationale

Removing the const or volatile qualification from a pointer or reference might be unexpected. Consider this code:

void foo(const char* p){
  *const_cast< char * >( p ) = '\0';
}
The function foo() accepts a const pointer to a char. The caller of this functions expects that the parameter p remains unchanged. Modifying p in foo() by converting it to a non-const pointer is unexpected. If *p dereferences to a const character, this modification might lead to unexpected behavior. Avoid casting the const or volatile away from a pointer or reference.

Polyspace Implementation

Polyspace® raises a violation of this rule if you remove the const or volatile qualification from the type of a pointer or a reference by using a casting operation.

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

void foo(const char* p){
  *const_cast< char * >( p ) = '\0';//Noncompliant
}

void foo1(volatile char* p){
  (char*) p ;//Noncompliant
}

In this example, Polyspace flags the casting operations that cast away the const and volatile qualifiers from pointers.

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019a

expand all