rspec/rules/S3687/cfamily/rule.adoc
Fred Tingaud 22b4470f2a
Modify CFamily rules: CPP-4080 Refresh and standardize CppCoreGuidelines references (#3514)
Update all links to C++ Core Guidelines to `e49158a`.

Refresh done using the following script and some manual edits:
db76e34e74/personal/fred-tingaud/rspec/refresh-cppcoreguidelines.py

When re-using this script, be mindful that:
 - it does not cover `shared_content`
 - it does not properly escape inline code in links (e.g., "[=]" or "`mutex`es")
 - it does not change `C++` to `{cpp}` in link titles.

Co-authored-by: Marco Borgeaud <marco.borgeaud@sonarsource.com>
2023-12-20 10:08:18 +01:00

71 lines
2.2 KiB
Plaintext

== 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 other languages that provide 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.
____
Only C11/{cpp}11 "atomic types" are free from data races, and you should use them or synchronization primitives if you want to avoid race conditions.
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
* 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]
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[]