How do I declare a static array with volatile elements? - c

Clarification about terminology used:
For static array I mean array statically memory allocated like: int x[10].
The problem
I need to declare a static array with volatile elements.
If I well understood how volatile qualifier works, it should be:
volatile uint8_t *x; // x is a pointer to volatile uint8_t
uint8_t *volatile x; // x is a volatile pointer to uint8_t
volatile uint8_t *volatile x; // x is a volatile pointer to volatile uint8_t
Ok, but now I need to do the same thing with a static array.
I tried with:
volatile uint8_t x[10]; // Only the pointer is decleared as volatile
uint8_t volatile x[10]; // Same as above
volatile uint8_t *x3[10]; // Casting problems and errors when I do ...
*x3[0] = 1; // ... something like this. Moreover, I do not know if this...
// ... statement declares the uint8_t element as volatile
Thanks!
UPDATE
Ok, as highlighted in the comments I should use:
volatile uint8_t x[10]
As I could understand, the problem is not in the declaration but in the usage of this variable in my code. I pass this element to a function whose prototype is:
static void functionName(uint8_t *buffer, uint32_t size);
I call the function in this way:
functionName(x, 10);
The compiler reports: passing argument 1 of 'functionName' discards 'volatile' qualifier from pointer target type
I can't change the function prototype, how can I solve the problem?

What you have to do to declare a static array of 10 volatile elements of type uint8_tis just:
volatile uint8_t x[10];
Be aware that this is a declaration of an array, which has nothing to see with pointers at this step.
Note: Later in your code, if you use x, it may decay to a pointer to the first volatile element, but in this case this pointer will have a constant value, given at the linking step. The pointed value is obviously volatile.

Stumbled across the problem myself today.
A variable CAN be 'sometimes' volatile.
Being volatile means, that its value can changed outside the program flow. By a parallel thread or an ISR.
Now if the ISR is what changes the value 'unexpectedly', it won't change unexpectedly inside the ISR itself. So for the ISR, the variable is not volatile and disabling compiler optimizations for it is counterproductive.
If I call a function from inside the ISR (and only from there), then the variable is not volatile and I don't want to pass a pointer to volatile, as it would produce inefficient code.
For this case, the solution I found was to have two declarations:
int a[x] = {};
volatile int * b = a;
Now the outside world uses b (globally declared in the header file) and treats the values pointed to by b as volatile, while the ISR (locally) defines both and uses a, treating the values as being not volatile.
Well, this is a very special case. In general, a function only sees the function parameter declaration. Which is either volatile or not, so the funciton will treat a parameter either always as being volatile or always as being not. It cannot automatically switch between two maybe completely differently compiled code blocks depending on the original volatile qualifier state of the passed parameter. Hence the warning.

Related

C - use of a volatile pointer

Why would one create a volatile pointer? And suppose I want a volatile pointer which points to a volatile variable, which of the following declarations would accomplish this:
volatile int *pData;
or
volatile int * volatile pData;
Why would one create a volatile pointer?
Example: To access data whose pointer is updated by a background process.
Stuff * volatile VideoFrame;
for (;;) {
Block_Changes();
Stuff MyCopy = *VideoFrame;
Allow_Changes();
Use(&MyCopy);
}
I want a volatile pointer which points to a volatile variable, which of the following declarations would accomplish this:
The 2nd meets the goal. volatile int * volatile pData; is a:
pData as volatile pointer to volatile int
The 1st volatile int *pData; is a non-volatile pointer to volatile data:
pData as pointer to volatile int
The volitle keyword is most often used in this context. # Eugene Sh.
One reason to use the modifier `volatile' is so the compiler does not optimize the variable out of existence.
Another reason to use the modifier 'volatile' is so when ever the code references that variable, it accesses the actual variable and not the value left in some register.
Another reason to use the modifier 'volatile' is when the variable value can change outside the control of the current program. For instance a hardware register or when an 'interrupt' updates the variable that your application is reading.

Casting volatile variable in c

I think I have a tricky question, but I'm sure you will be able to help me.
Let's say I have a function like this:
char my_function (int example);
I use this function in multiple cases, sometimes the argument it receives is a volatile variable and sometimes a non-volatile variable.
That cause some warnings when I compile my code that can be easily removed by using casts, but I want to understand which is the safer scenario and why.
Scenario 1:
Prototype: char my_function (int example);
int a;
volatile int b;
my_function (a); // Everything is fine.
my_function ((int)b); // Avoided the warning, by casting the variable and saying it's no longer volatile.
Scenario 2:
Prototype: char my_function (volatile int example);
int a;
volatile int b;
my_function(b); // Everything is fine.
my_function((volatile int)a); // Avoided the warning, by casting 'a' saying that now it's volatile.
I understand how volatile modifier works, I mostly use it because I program micro-controllers and I need to ensure that some of my variables are never optimized out when they are hardware modified.
I am a bit confused about casting the volatile modifier and that is why I want to understand which is the safer scenario apart from just removing the warning.
It really depends on what my_function does with its argument.
Remember that volatile prevents certain optimizations - predominantly it forces the variable to be re-read every time it is referenced. Thus this code
volatile int a;
int b;
// ...
b = a + 1;
b = a + 2;
will read a for each statement and, as a may have changed values between them, give the correct result.
When you pass a volatile into a function as a parameter, you only get one read of the variable. This may then be used multiple times within the function (effectively losing the volatile nature).
Remember that C is pass-by-value. When you invoke the function as
my_function((int)b); // b is declared volatile
The compiler generates code to read b once in the calling code, and push the value it read onto the stack (usually), then invoke my_function. This copy is then referenced within my_function as example, and no matter how often you reference example you will always get the same value (even if the original b variable has since changed many times).
That might be exactly what you want - take a snapshot of the variable and do several computations on its value.
If it's not what you want, you need to consider passing in a pointer with the appropriate volatile qualifications.
char my_function( volatile int *example);
And call it thus:
my_function(&a);
my_function(&b);
Then reference *example inside my_function.
The cast doesn't actually do anything. In the call my_function (b); the code reads the volatile int b. That's where the "volatile" matters, during the read. The result of the read is already an int and not a volatile int. There are no volatile int values. Even if there were volatile int values, passing it to my_function would convert it to plain int, just as the cast does.
It may be that the compiler assumes that passing a volatile int variable to a function is something dangerous worth a warning, and by adding a cast to int you indicate that you know what you are doing.

Any optimization removes code (volatile pointer to array)

I'm writing simple code in C for STM32F0 discovery board. I'm generating different waveforms, according to external analog signal.
Declared global arrays with waveforms:
const uint32_t sinus[WAVELENGHTS] = {128,131,134,137,141,...}
const uint32_t square[WAVELENGHTS] = {0,0,0,0,0,0,0,0,0,0,...}
and pointer to array
const uint32_t (*currentWave)[WAVELENGHTS];
That pointer is used in timer irq to generate chosen waveform:
void TIM14_IRQHandler()
{
...
TIM2->CCR1 = (*currentWave)[(mainSynth.DDSAccumulator)>>24];
TIM14->SR &= ~(TIM_SR_CC1IF);
}
According to external value, in main loop I choose one of waveforms:
while(1) {
...
if(ADC_values[2] < 2048)
currentWave = &sinus;
else
currentWave = &square;
...
}
Without optimizations, currentWave value changes according to ADC_values[2] change (exactly: to TIM2->CCR1 are written values from good waveform, sinus or square), but enabling any optimization makes code working bad, it means assignment
currentWave = &sinus;
or
currentWave = &square;
never executes, currentWave always have initial value.
I also tried to declare both pointer and arrays as volatile, with no effect.
I need optimization for size to fit code in my device.
Any ideas?
I'm going to make a wild guess: you tried the volatile this way and it didn't work:
const volatile uint32_t (*currentWave)[WAVELENGHTS];
And that is to be expected, because this declaration makes volatile the uint32_t values of the array, not the pointer. And the pointer is what changes asynchronously.
Try instead:
const uint32_t (* volatile currentWave)[WAVELENGHTS];
And see what happens.
Note: if you find the syntax awkward, try with typedefs:
typedef const uint32_t waveform_t[WAVELENGHTS];
waveform_t *volatile currentWave;
You could even do:
typedef waveform_t *waveform_ptr;
volatile waveform_ptr currentWave;
but I find it excessive.
I guess you could try make the pointer volatile. Be sure not to just declare it a pointer to volatile uint32_t values, but to declare the pointer itself as volatile. My guess is that the compiler ignores it if the pointer itself is not volatile.
const volatile uint32_t *currentWave; <- "pointer" to "const volatile memory"
const uint32_t * volatile currentWave; <- "volatile pointer" to "const memory"
Also, I think there is no need for that extra indirection, you can just use a pointer, and assiging it like:
currentWave = sinus;
is perfectly valid, just as indexing it like
currentWave[(mainSynth.DDSAccumulator)>>24]
is valid C code.

How to create fixed array of volatile struct function pointers

How does one create an array of volatile structs? Each struct contains 3 function pointers.
i.e. is it
State_t * volatile states[10];
or
volatile State_t * states[10];
??
Also, should the struct properties be defined as volatile as well?
This is to ensure function pointers are not cleared by compiler. Code works fine when compiled with GCC. However, the second entry in the array returns rubbish compiled with the ARM compiler for Cortex-M3.
State_t *volatile states[10];
The above means states is an array of 10 volatile pointers to objects of type State_t. The volatile keyword here qualifies the pointers, not the value pointed to.
State_t volatile *states[10];
The above means states is an array of 10 pointers to objects of type volatile State_t. Here, the volatile keyword qualifies not the the pointer, but the value pointed to. The above can also be written as
volatile State_t *states[10];
To answer the latter part of your question, if you qualify a structure variable as volatile, then all its members are volatile. However, the volatile qualification is not part of the structure definition.
volatile struct states {
// stuff
} state_a;
struct states state_b;
Here, state_a is volatile qualified but state_b is not. Therefore, you need to qualify each states instance explicitly as volatile unless you create states instances in the same statement as the structure definition.

Argument of type "volatile char *" is incompatible with parameter of type "const char *"

I have a function whose prototype is as follows:
void foo(const char * data);
Elsewhere in my code, I have a global variable declared as follows
volatile char var[100];
Whenever I try to do this:
foo(var);
The compiler throws up the following error message:
Argument of type "volatile char *" is incompatible with parameter of type "const char *"
Why is that the case? As I understand it, the variable in my function is not allowed to change the pointer or its contents. I understand that because my global variable is volatile, it could potentially change at any time, but seeing as it is perfectly legal to have a volatile const variable, I don't see why I am getting this compiler error.
Thanks
--Amr
It's because implicit conversions can add qualifiers to the target of pointer types, but not remove them. So if you want your function to be able to accept volatile and/or const qualified pointers, you must declare it with both:
void foo(const volatile char * data);
Because accessing a volatile variable using pointer to non-volatile is wrong. Either the object is volatile and then it should be accessed as such everywhere or you can access it as non-volatile and then it should not be marked as such. Make up your mind.
If you want to handle a volatile argument in your function you must declare it as such:
void foo(const volatile char * data);
This would do the trick. But be aware that this also brings you all the overhead of volatile to the implementation of foo, i.e data[something] will be reloaded from memory at any point that you access it.
(Generally volatile is not so much of a good idea, unless you are doing device drivers or so. Even for parallel processing with threads it usually doesn't guarantee what you expect at first sight.)

Resources