Search code examples
cvolatile

Usage wise difference between const & volatile qualifier in C?


I have already gone through the answer of question @ What are the differences between const and volatile pointer in C? I understand the explanation that:

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. However, volatile says "this data might be changed by someone else" and so the compiler will not make any assumptions about that data.

Which implies that both type of variables can be changed by external event.

But,then where is the difference in usage of const & volatile?

In C, does compiler optimizations work for const?


Solution

  • volatile and const are different in many ways, they are two distinctively different features.

    Declaring a variable just as const never means "I expect this variable to be modified outside the program", I'm not sure where you got that idea from. If you expect a const variable to be modified outside the code, it must be declared as volatile const or the compiler may assume that the variable is never changed.

    By default, plain const variables are just like any kind of variable, they simply can't be modified by the program itself.

    Just as for plain variables, const variable behavior depends a lot on in which scope they are declared. Most often they are declared at file scope and then they behave as other variables with static storage duration, except they are (likely) saved at a different part of the memory. If they are declared at local scope, they may change from time to time when the function where they reside is called.

    So there are plenty of cases where const variables may be optimized. One common optimization is "string pools", where the compiler checks if the same constant string literal appears twice in the code, and then uses the same address for them. Had you expected such strings to be changed from an external source, but didn't declare them as volatile, you'd get strange bugs.

    As for volatile variables, they may be modified by external sources, but they may also be modified by the program, unlike const variables.