Monday, May 24, 2010

Const & Volatile

Const and Volatile are not opposite of each other!

Const - A variable whose value can not be changed, that is a constant. A programmer can not change the value of a variable declared as constant later in program. If it is not initialized at deceleration, it can not be assigned/initialized later.

An integer constant can be defined as:

const int myConst = 10;
int const myConst = 10;

Both the declaration have the same meaning. But in case of pointers, things are different.

const int *myPtr = (int *)0xFFFFFF04;     /* 1 */
int const *myPtr = (int *)0xFFFFFF05;     /* 2 */
int* const myPtr = (int *)0xFFFFFF06;     /* 3 */

Declaration 1 & 2 are the same and indicates the myPtr is an ordinary integer pointer and the integer pointed by it can not be modified. As a programmer, I can modify myPtr as:

int anInt = 10;
myPtr = &anInt;

But I can not do:

*myPtr = anInt;

However, the deceleration 3 defines a pointer myPtr that can not be modified but the value pointer by it can be modified.


Const, actually volatile also, variables are useful in real-time C programs. A const variable may never be initialized. An use case of this can be a the address of memory mapped I/O which is read only.

Volatile - Linux for you and Netrino articles have clearly explained volatile keyword. So, I will just be summarizing it here.

When a programmer declares a variable volatile, (s)he informs the compiler that the variable at any time during the life of program can change its value, so be careful while optimizing the code. In reference to the example of memory mapped I/O, I would define a pointer holding the address as a const variable but the value pointed by as volatile.

volatile int* const memIO = 0xFFFFFF05;

Some more declerations.

int volatile alcohol;
volatile int alcohol;            /* are the same - alcohol is volatile */

Now the pointer and volatile.

volatile int *myPtr;                    /* ordinary integer pointer to volatile integer data*/
int* volatile myPtr;                    /* volatile integer pointer to usual integer data*/
volatile int* volatile myPtr;       /* volatile integer pointer to volatile integer data*/ 


Now do NOT confuse in an interview.

Usage of volatile variable (as pointer in Netrino article)
  • Memory-mapped peripheral registers
  • Global variables modified by an interrupt service routine
  • Global variables accessed by multiple tasks within a multi-threaded application
What does volatile long * const timer = 0x0000ABCD mean?

Have fun!

No comments:

Post a Comment