In C++, it usually does not matter how many times you access a variable as long as the variable value is the right one. However, this is not the
case when the variable is in a memory region mapped to external hardware. In that case, for instance, several successive reads can yield different
values (if the memory is updated by the hardware in-between), and several writes of the same value may be significant (some hardware trigger events
each time a memory location is written to).
To specify that every read and write has an impact outside of the abstract machine of the language, access to a variable may be qualified as
volatile
: it will oblige the program to perform all specified reads and writes operations without optimizing anything away.
When a variable appears in a compound expression (for instance, a++
or a+=2
), the variable is accessed twice even if it
is only named once. The standard was not explicit on this topic up until C++23, but this detail matters for volatile
variables for which
every access to the variable matters.
Consequently, it is usually clearer to rewrite the code so that the variable appears twice, matching the number of accesses that will happen.
Note: In C++20, compound expressions on volatile variables were deprecated. This deprecation was removed in C++23, and the number of accesses was
made explicit. The reason for removing the deprecation is that such operations are commonly used in embedded code, especially to access specific
variable bits. However, using a function with a dedicated name instead of direct bit manipulation usually leads to code that is easier to read.