Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

c++ - Does "const" just mean read-only or something more?

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.

question from:https://stackoverflow.com/questions/4486326/does-const-just-mean-read-only-or-something-more

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...