Welcome to graduate2professional.blogspot.com

Tuesday, July 14, 2009

Constant Vs Volatile variables

Constant variables:
The const type qualifier declares an object/variable to be nonmodifiable but optimization can be done on it.

Volatile variables:
Volatile is a qualifier that is applied to a variable.A variable should be declared volatile whenever its value could change unexpectedly and no optimization is done on it.

In practice, only three types of variables could change:
a.Memory-mapped peripheral registers
b.Global variables modified by an interrupt service routine
c.Global variables within a multi-threaded application

If we do not use volatile qualifier the following problems may arise:
1.Code that works fine-until you turn optimization on
2.Code that works fine-as long as interrupts are disabled
3.Flaky hardware drivers
4.Tasks that work fine in isolation-yet crash when another task is enabled

The volatile specifier disables various optimizations that a compiler might automatically apply and thus introduce bugs.
1) Some hardware interfacing applications periodically read values from a hardware port and copy it to a local variable for further processing. A good example is a timer function that reads the current count from an external clock. If the variable is const, the compiler might skip subsequent reads to make the code more efficient and store the result in a CPU register. To force it to read from the port every time the code accesses it, declare the variable const volatile.

2) In multithreaded applications, thread A might change a shared variable behind thread B’s back. Because the compiler doesn’t see any code that changes the value in thread B, it could assume that B’s value has remained unchanged and store it in a CPU register instead of reading it from the main memory. Alas, if thread A changes the variable’s value between two invocations of thread B, the latter will have have an incorrect value. To force the compiler not to store a variable in a register, declare it volatile.

Constant volatile variables:
Can a variable be both Constant and Volatile?
Yes. An example is a read-only status register. It is volatile because it can change
unexpectedly. It is const because the program should not attempt to modify it

No comments:

Post a Comment