且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

难道" const的"仅仅意味着只读或更多的东西?

更新时间:2023-02-15 21:14:42

通过声明一个变量常量表示您没有修改该变量的意图编译器。不过,这并不意味着人无我有!这只是让一些优化,并通过编译错误通知(注意,这是大多编译错误,而常量==只读将意味着运行时错误)。

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 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.

编辑:这是一个经典的例子:考虑我写了code,它读取内存映射端口当前时间。考虑到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;

这是常量,因为它是一个只读端口,它的挥发性因为每次我会读它,它会发生变化。

It's const because it's a read-only port, and it's volatile because each time I will read it it will change.

另外请注意,许多体系有效地使声明为常量全球varialbles 只读的,因为它是UB修改它们。在这种情况下UB将自己表现为一个运行时错误。在其他情况下,这将是一个真正的UB:)

Also note that many architectures effectively makes global varialbles 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