Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Should I qualify pointer parameters with volatile if they may be changed during the execution of a function?

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");
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading