== Why is this an issue?

The main intended use-case for ``++volatile++`` in C and {cpp} is to access data that can be modified by something external to the program, typically some hardware register. In contrast with some other languages with a ``++volatile++`` keyword, it does not provide any useful guarantees related to atomicity, memory ordering, or inter-thread synchronization. It is only really needed for the kind of low-level code found in kernels or embedded software, i.e. using memory-mapped I/O registers to manipulate hardware directly. 


According to the C standard:

____
``++volatile++`` is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.
____

Local variables and data members are completely controlled by the {cpp} language. This means they can't change their value without the compiler knowing about it. Therefore, it doesn't make sense for them to be marked as `volatile`.

If the intent is to share those variables between threads, race conditions can be avoided by using synchronization primitives (such as `std::mutex`) or atomic types (``++_Atomic++`` in C11, `std::atomic<T>` in {cpp}11).

This rule raises an issue when a local variable or class data member is declared as ``++volatile++`` (at the top level of the type, pointers to volatile are not reported).


=== Noncompliant code example

[source,cpp]
----
volatile int counter; // Noncompliant
User * volatile vpUser; // Noncompliant; pointer is volatile 
User volatile * pvUser;  // Compliant; User instance is volatile, not the pointer
----


=== Compliant solution

[source,cpp]
----
atomic_int counter;
std::atomic<User*> vpUser;
User volatile * pvUser;
----


== Resources

=== Standards

* https://wiki.sei.cmu.edu/confluence/display/c/CON02-C.+Do+not+use+volatile+as+a+synchronization+primitive[CERT CON02-C] - Do not use volatile as a synchronization primitive
* {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#cp200-use-volatile-only-to-talk-to-non-c-memory[CP.200: Use `volatile` only to talk to non-{cpp} memory]
* STIG Viewer - https://stigviewer.com/stig/application_security_and_development/2023-06-08/finding/V-222567[Application Security and Development: V-222567] - The application must not be vulnerable to race conditions.


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Convert this "volatile" type into an atomic type.


=== Highlighting

volatile keyword


'''
== Comments And Links
(visible only on this page)

=== is related to: S3475

=== on 27 Jul 2016, 15:49:26 Ann Campbell wrote:
Okay [~alban.auzeill], double-check me.

endif::env-github,rspecator-view[]
