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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…