C: Volatile Arrays in C C: Volatile Arrays in C c c

C: Volatile Arrays in C


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


Filipe Gonçalves have already provided an answer, but I would like to elaborate a bit.

Basically, the volatile keyword is required whenever you would like your program to really consider the variable value, without trying to be smart. It does not matter what kind of variable you have, it's just that if compiler can't see any changes to a variable between the assignment and the call, it will probably optimize it (depending on your settings of course).

From compiler's POV, the sequence of events is "assign 0 to Var"->"do unrelated stuff, but surely not touching Var"->"check Var value" It does not matter where and how variable Var got declared, and the code will be optimized unless volatile keyword is used.


C declarations are to be read form right to left with qualifiers to the left.

So volatile char * x means 'x' is a pointer to a volatile char.while char volatile * x means that 'x' is a volatile pointer to a char

The difference in pactice is that when accessing x[0], in the first case, the value at x[n] needs to be read on each appearance in the source code (e.g. twice in a = x[n]*x[n])

In the second case, x iteself needs to be read each time and then the address of x[n] needs to be calculated again and then x[n] is to be read.

For this reason, volatile char volatile *x is redundant.

However, declaring an array or its elements as volatile will prevent the compiler from buffering them across multiple reads. It does not ensure that a function that reads a volatile array won't read first half of the array while it contains old values and (after an external change) the second half while it contains updated values, leading to an inconsistent result.Using volatile on arrays or structs (or sets of individual variables) is only advisable when the individual elements are independent of each other. If changing one of them affects the others (or their use/meaning), then volatile won't help at all and a mutex should be used for the whole access (preventing the array content to be changed during processing).