I was wondering if in the following scenario a temporary volatile qualifier would yield correct behavior. Assume an ISR collects values in an array and once enough values have been collected it signals readiness.
int array[10]; // observe no volatile here
int idx = 0; // neither here
volatile bool ready = false; // but here
Here's the ISR is pseudo-code
ISR() {
if (idx < 10)
array[idx++] = ...;
ready = (idx >= 10);
}
Assume we can guarantee that array
will be read only after ready
is signalled, and elements are accessed via specific method only:
int read(int idx) {
// temporary volatile semantics
volatile int *e = (volatile int*)(array + idx);
return *e;
}
which seems to be allowed according to cpp-reference
A cast of a non-volatile value to a volatile type has no effect. To access a non-volatile object using volatile semantics, its address must be cast to a pointer-to-volatile and then the access must be made through that pointer.
For completeness the main routine does the following
void loop() {
if (ready) {
int val = read(0); // Read value
// do something with val.
}
}
In such a scenario should I expect to read correct values from array
or is volatile on the array elements required to guarantee that writing to the array from within ISR()
is actually performed in RAM?
Note that Why is volatile needed in C? does not detail whether or not in this special case volatile is needed.
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value.
A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change: Memory-mapped peripheral registers. Global variables modified by an interrupt service routine.
C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby.
The write to array[]
is not through volatile
, so you can't rely on that being observable behavior. Yes, the compiler must issue a non-cached read of array
, but that is only half of the picture.
You're talking about order as if that's affected by volatile
- it isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With