C: Volatile Arrays in C

user3728501 picture user3728501 · Aug 15, 2014 · Viewed 12.2k times · Source

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++?

Answer

Filipe Gonçalves picture Filipe Gonçalves · Aug 15, 2014

Yes, volatile is required, and the right declaration is:

volatile unsigned char *my_data;

This declares my_data to be a pointer to volatile unsigned char.

To make the pointer itself volatile, you'd need this instead:

unsigned char *volatile my_data;

And of course, both the pointer and the pointed-to data may be volatile:

volatile unsigned char *volatile my_data;

There's no difference between C and C++.