This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 10.1.2 - The volatile qualifier shall be used appropriately
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
It is inappropriate to declare the following entities as volatile:
- Local variables;
- Function parameters;
- Function return types;
- Member functions;
- Structured bindings.
Note: a pointer or reference to a volatile entity is permitted.
Rationale
While the C++ Standard permits volatile qualification to be applied to the entities listed above, the behaviour is not
well-defined or well-understood. In addition, volatile does not prevent data races, but it is often incorrectly used when trying to
ensure thread safety.
Note: some of these uses of volatile have been deprecated in C++20 and their removal is planned for a future
version.
Example
void f1( volatile int32_t i ) // Non-compliant
{
use< int32_t >( i );
}
void f2( volatile int32_t * p ) // Compliant - parameter is not volatile
{
use< int32_t * >( p );
}
void f3( int32_t * volatile p ) // Non-compliant - parameter is volatile
{
use< int32_t * >( p );
}
void f4( int32_t i )
{
volatile int32_t j = i; // Non-compliant
use< int32_t >( j );
}
volatile int32_t f5(); // Non-compliant
void f6()
{
int32_t g[ 2 ] = { 1, 2 };
auto volatile [ a, b ] = g; // Non-compliant
}
struct S
{
volatile uint32_t reg; // Compliant
};
void f7( S s ); // Compliant - but unlikely to work as expected
void f8( S & s ); // Compliant - preserves volatile behaviour of reg
Copyright The MISRA Consortium Limited © 2023