const
QualifierSometimes we want to define a variable whose value we know cannot be changed. For example, we might want to use a variable to refer to the size of a buffer size. Using a variable makes it easy for us to change the size of the buffer if we decided the original size wasn’t what we needed. On the other hand, we’d also like to prevent code from inadvertently giving a new value to the variable we use to represent the buffer size. We can make a variable unchangeable by defining the variable’s type as const
:
const int bufSize = 512; // input buffer size
defines bufSize
as a constant. Any attempt to assign to bufSize
is an error:
bufSize = 512; // error: attempt to write to const object
Because we can’t change the value of a const
object after we create it, it must be initialized. As usual, the initializer may be an arbitrarily complicated expression:
const int i = get_size(); // ok: initialized at run time
const int j = 42; // ok: initialized at compile time
const int k; // error: k is uninitialized const