Consider these two definitions:
volatile int a[10];
volatile int *p = a;
EDIT: clarify question.
If we refer to a[3]
that memory location will be treated as volatile
storage, that is, the compiler will make no assumptions about it staying the same.
For an array, it is clear that the intention is that the entire contents of the array are treated as volatile
.
Is it the case also in C that p[3]
also refers to volatile
storage, though p
is declared as a pointer, and not as an array? In other words, in an expression using a "pointer to volatile
", such as p[3]
or *(p + 3)
is the volatile
"infectious", and does it apply to memory locations other than the exact one pointed to by the pointer to volatile
?
I do know what it means for the compiler to treat memory as volatile.
Is it the case in C that p[3] also refers to volatile storage...
Yes, volatile int *p
makes p
a pointer to volatile int. So any access made using p
(aka dereference of p
) will be considered a volatile access to memory.
Note that p
itself isn't volatile. It's only what p
points to that are volatile.
Not that it's a proof but for fun, you can try removing "volatile" from p
like:
volatile int a[10];
int *p = a;
Compiling this with e.g. gcc
gives you a warning like:
warning: initialization discards 'volatile' qualifier from pointer target type [-Wdiscarded-qualifiers]
which makes it pretty clear that something is wrong as p
no longer points to volatile int.
BTW:
Constant pointer vs Pointer to constant could be an interesting read. It's about const
instead of volatile
but the principle is the same.