There is a lot to the const keyword, it is a rather complex one. Generally, adding a lot of const to your program is considered good programming practice, search the web for "const correctness" and you'll find plenty of info about that.
The const keyword is a so-called "type qualifier", others are volatile and restrict. At least volatile follows the same (confusing) rules as const.
First of all, the const keyword serves two purposes. The most obvious one is to protect data (and pointers) from intentional or accidental misuse by making them read-only. Any attempt to modify a const variable will be spotted by the compiler at compile-time.
But there is also another purpose in any system with read-only memory, namely to ensure that a certain variable is allocated inside such memory - it could be EEPROM or flash for example. These are known as non-volatile memories, NVM. A variable allocated in NVM will still of course follow all the rules of a const variable.
There are several different ways to use the const keyword:
Declare a constant variable.
This can be done either as
const int X=1; or
int const X=1;
These two forms are completely equivalent. The latter style is considered bad style and should not be used.
The reason why the second row is considered bad style, is probably because "storage-class specifiers" such as static and extern also can be declared after the actual type, int static etc. But doing so for storage-class specifiers is labelled as an obsolete feature by the C committee (ISO 9899 N1539 draft, 6.11.5). Therefore, for the sake of consistency one should not write type qualifiers in that manner either. It serves no other purpose but to confuse the reader anyhow.
Declare a pointer to a constant variable.
const int* pt
answered 2011-10-10T19:01:28.437