Search code examples
cembeddedvolatile

Reason for volatile nonstatic local variable in C


Refer to the following code:

void calledFunction(volatile uint8_t **inPtr);
volatile uint8_t buffer[] = {0,0,0,0,0,0}; 

volatile uint8_t *headPtr = buffer;

void foo(void)
{
    volatile uint8_t *tmpPtr = NULL;

    tmpPtr = headPtr;

    //This function modifies tmpPtr
    calledFunction(&tmpPtr);

    headPtr = tmpPtr;
    return;
}

This is a simplified version of code that I am attempting to make interrupt-safe, and I am not sure why this local is defined as a volatile. I know that there is no performance reason (i.e. to guarantee at least O(n) for this function) because this function should run as efficiently as possible.

This function can be called in both main execution and inside interrupts, but since tmpPtr is a nonstatic local variable, it should not be able to be modified by any other instance of foo().

I can't see any access pattern that would require the volatile keyword in this context.

In short, What is the purpose of the volatile keyword for tmpPtr in function foo()?

EDIT:Forgot a & in function argument

EDIT2: I have inherited this code and need to modify it. My main question is whether the volatile keyword has any special effective reason for being in this context.

EDIT3: Added the prototype for calledFunction()

EDIT4: Added important clarification in original code that headPtr and buffer both have volatile


Solution

  • The reason tmpPtr has volatile is due to tmpPtr needing to reference a volatile uint8_t, not because tmpPtr itself is volatile (it isn't).

    As initially pointed out by @Eugene Sh., this question came up due to a misunderstanding in syntax when defining volatile pointers and variables. This question has a great explanation of syntax for pointers to volatile vs volatile pointers.