The volatile keyword is used in C to prevent the compiler performing certain optimizations, amongst other subtle changes, on a variable.
For example;
volatile int my_int = 0;
creates an integer. In some situations it may prevent the following optimization:
while(my_int == 0); // Loop until my_int != 0
Optimize to:
while(1); // Loop infinity.
This is useful for situations including those frequently encountered in embedded systems, such as a situation where modification to a variable may be made by an interrupt function call. There are many other examples of where this technique is useful. my_int
may be a flag which is modified by such a function. (This is just a toy model.)
However, consider the case where the data modified by the function is an array. The data may be pointed to by a pointer.
unsigned char* my_data = new unsigned char[256];
In this case, considering that my_data is a global variable in this specific situation of this question[1], is the volatile
keyword redundant, or is it still required?
[1] It may not matter.
If the answer is that the volatile keyword is required, what it the correct syntax for use?
For example, volatile unsigned char* my_data
, I assume declares that the pointer itself is volatile, and not the data it points to.
Finally, is there a difference between the use in C and C++?
my_int
being declared asvolatile
. Reason being that the compiler must know that the value is zero from the start of the loop, and that it will never be changed in the loop. – Booteevolatile
works, rather than its purpose. – Kinkstd::array
. This would result instd::array<volatile char, N> data;
making it obvious thatchar
isvolatile
.N
will usually be some number, e.g.5
:std::array<volatile char, 5> fiveChars;
. Of course iterators to specific elements can be volatile as well:volatile auto itr = std::begin(fiveChars);
– Stuff