Thursday, October 21, 2010

const and volatile

an a variable be both const and volatile?
Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example in
FAQ 8, the timer structure was accessed through a volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.

This is possible and mostly used in embedded system.The example is Interrupt Status Register.As it is a status register , in the program we should not modify this variable.So it should be a constant.But this variable can be changed by the processor or hardware based on the interrupt condition.So when in the program ,we want to read the value of this varible , it should read the actual value with out any optimisation.For this reason ,the variable can be declared as volatile too.

No comments:

Post a Comment