In the C language, when an identifier is declared to be const
, no writes are allowed to it.
When reading a const declaration, read backwards:
const char x // x is a char that is const const char *y // y is a pointer to a char that is const char * const z // z is a const pointer to a char y = "hello"; // legal, pointer is not const *y = '\0'; // illegal, changes contents z = "hello"; // illegal, changes pointer *z = '\0'; // legal, contents are not const
Why use const
const
enforces a certain form of type-safety. If some piece of memory isn't meant to be changed in a given scope, declare it to be const
and the compiler will help you ensure that it isn't inadvertently written to.
const
is mostly a good habit for defensive programming. I haven't found a situation where it helps the compiler produce more optimal code.