Main Content

MISRA C++:2023 Rule 8.2.3

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

Since R2024b

Description

Rule Definition

A cast shall not remove any const or volatile qualification from the type accessed via a pointer or by reference. 1

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_t * >( 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.

Because references themselves are not objects, the C++ standard does not allow references to be CV qualified. If you add CV qualifiers to a reference using typedefs, decltype specifiers, or template parameter, Polyspace ignores the CV qualifications. For example, when using reinterprt_cast to cast to a reference type, Polyspace ignores the CV qualifier in the casting expression, which can result in a violation of this rule. In this code, the const qualifier in the reinterpret_cast expression is ignored.

void func(const int);

void bar (const int var){
    func(reinterpret_cast<const int&>(var)); 
    // equivalent to func(reinterpret_cast<int&>(var))
} 
Polyspace reports a violation because the const int variable var is cast into a int&.

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

Version History

Introduced in R2024b


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.