问题描述
const
的真正含义是什么?只读对我来说似乎封装了它的含义,但是,我不确定我是对的.
What does const
really mean? Read-only seems to encapsulate its meaning for me, but, I'm not sure I'm right.
如果只读和 const
不同,谁能告诉我为什么?
If read-only and const
are different, could someone tell me why?
提出这个问题的原因是 this answer 其中他声明 const
只是"意味着阅读- 仅在 C 中.我认为这是 all const
的意思,无论它是 C 还是 C++.他是什么意思?
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?
为了回答 C 与 C++ 中 const
的具体差异,我创建了一个新问题:const"如何?C 和 C++ 不同? 根据 R.. 的建议.
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.
推荐答案
通过将变量声明为 const
表示编译器您无意修改该变量.但这并不意味着其他人没有!它只是为了允许一些优化并通过编译错误得到通知(注意,它主要是编译错误,而 const == ReadOnly
意味着运行时错误).
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
不代表只读,因为你可以写const volatile
,也就是说可以随时自行改变,但我无意修改它.
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.
这是一个经典示例:考虑我正在编写从内存映射端口读取当前时间的代码.考虑 RTC 映射到内存 DWORD 0x1234.
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;
它是 const
因为它是一个只读端口,它是 volatile
因为我每次阅读它都会改变它.
It's const
because it's a read-only port, and it's volatile
because each time I will read it it will change.
还请注意,许多架构有效地将声明为 const
的全局变量设为只读,因为修改它们是 UB.在这些情况下,UB 将表现为运行时错误.在其他情况下,这将是一个真正的 UB :)
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 :)
这是一个很好的阅读:http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html
这篇关于是否“const"?只是意味着只读或更多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!