Home > front end >  Should I qualify pointer parameters with volatile if they may be changed during the execution of a f
Should I qualify pointer parameters with volatile if they may be changed during the execution of a f

Time:03-23

Say I have the function

int foo(int * const bar){
    while(!*bar){
        printf("qwertyuiop\n");
    }
}

where I intend to change the value at bar to something other than 0 to stop this loop. Would it be appropriate to instead write it as below?

int foo(int volatile * const bar){
    while(!*bar){
        printf("qwertyuiop\n");
    }
}

CodePudding user response:

volatile was intended for things like memory-mapped device registers, where the pointed-to value could "magically" change "behind the compiler's back" due to the nature of the hardware involved. Assuming you're not writing code that deals with special hardware that might "spontaneously" change the value that bar points to, then you needn't (and shouldn't) use the volatile keyword. Simply omitting the const keyword is sufficient to let the compiler (and any programmer that might call the function) know that the pointed-to value is subject to change.

Note that if you are intending to set *bar from another thread, then the volatile keyword isn't good enough; even if you tag the pointer volatile, the compiler still won't guarantee correct handling. For that use-case to work correctly, you need to either synchronize all reads and writes to *bar with a mutex, or alternatively use a std::atomic<int> instead of a plain int.

  • Related