What does const
really mean? Read-only seems to encapsulate its meaning for me, but, I'm not sure I'm right.
If read-only and const
are different, could someone tell me why?
What prompted this question was this answer where he states const
"just" means read-only in C. I thought that's all const
meant, regardless of whether it was C or C++. What does he mean?
For an answer to the specific differences in const
in C vs C++, I've created a new question: How does "const" differ in C and C++? as per R..'s suggestion.
By declaring a variable as const
you indicate compiler that you have no intentions of modifying that variable. But it does not mean others don't have! It's just to allow some optimization and to be notified by a compile error (note, that it's mostly compile error, while const == ReadOnly
would mean runtime errors).
const
does not mean read only, because you can write const volatile
, that would mean it could change by itself anytime, but I have no intentions to modify it.
EDIT: here is a classical example: consider I'm writing the code that reads current time from a memory-mapped port. Consider that RTC is mapped to memory DWORD 0x1234.
const volatile DWORD* now = (DWORD*)0x1234;
It's const
because it's a read-only port, and it's volatile
because each time I will read it it will change.
Also note that many architectures effectively make global variables declared as const
read-only because it's UB to modify them. In these cases UB will manifest itself as a runtime-error. In other cases it would be a real UB :)
Here is a good reading: http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html