Friday, June 8, 2007

const vs volatile

type-qualifiers

What is the volatile modifier?
---------------------------------
The volatile modifier is like the const modifier. The term used in the C++ standard is qualifier rather than modifier. Const and volatile are qualifications that can be applied to types. In fact where you can use const you can use volatile so a type can be neither const nor volatile qualified, const qualified, volatile qualified or const volatile qualified. The language is so regular in this respect that the standard uses the terms like 'cv-qualifiers' and 'cv-qualified', cv being short hand for const-volatile.


What is the difference between a volatile and non volatile variable?
-----------------------------------------------------------------------
A volatile qualification on a type is a hint to the compiler that objects (variables) of that type are likely to change or be read outside of the control of the program under compilation, hence the compiler cannot assume anything with regard to optimization.


Where should I use it or where not?
--------------------------------------
In nearly all standard application code there is no reason to use volatile. The exceptions are where you are interfacing with devices or possibly certain situations involving multithreaded code (although volatile is no help on its own with synchronisation problems).

For example if you have some object that is mapped to some memory mapped device register and this device's documentation states you have to write zero twice to this register for it to perform some action you would write some code like the following:

*pRegister = 0;
*pRegister = 0;

Now if the type pointed to is not volatile then the compiler is free to say: "Hang on this code is stupid, I'll just remove one of the writes of zero to this location, the result will be the same". By qualifying the type of the register as volatile the compiler will say "Hmm, this location is volatile, this means there are things going on here I am not aware of, I'll leave well alone and assume they know what they are doing".

Volatile can be used with function overloading. Just as a const qualified type passed to a function is different for overloading purposes to a cv-unqualified type, so is a volatile and const volatile qualified type. The same goes for class instance member functions: you can have cv-unqualified and const qualified member functions (as is quite common), but you can also have volatile qualified and const-volatile qualified instance member functions, and you can overload on all these qualification variations.

No comments: