Search This Blog

Friday, February 4, 2011

Best programming practice (C/C++): When and where to use volatile keyword

Main usage of volatile seen in embedded space. Practical use is seen in
1) Memory mapped peripheral registers 2) Global variables modified by ISR routine 3) Global variables modified by multi-threaded environment. In these scenarios values of these variable can change unexpectedly.

Watch out for the below behaviours and first thing to look for is assessing for the need for volatile variables.
Code stops working when
1) Multithreaded environment but works in single process/threads
2) Enable optimization
3) Enable Interrupts

Volatile qualifier will be used when the variable is declared, which tells the compiler that value of the variable can change without any action taken by code.

volatile int myVolatile;
int volatile myVolatile;
What is the difference between two?
If you do not know the answer let me know.

int * volatile myVolatile;
This means volatile pointer to non volatile variable.
int volatile * volatile myVolatile;
Volatile pointer to Volatile variable.

No comments:

Post a Comment