tags:

views:

114

answers:

5

When making something const in C++ what makes it that you cannot for example implicitly pass it a non-const at the lower levels of the machine? How is it determined by the machine that this is const?

(besides the fact that const means what it means...)

Is it perhaps stored in the .rdata section of memory or is there a bit that gets set that makes it const or how does that work?

Can anyone clarify?

+7  A: 

const-ness is almost always enforced by the compiler, nothing more, nothing less. No machine protection at all.

Edit: @Oli Charlesworth's answer is better than mine.

Paul Tomblin
It's worth remembering that smart compilers can also use this info during optimization phase.
Luca Martini
+11  A: 

const is mostly a compile-time thing; it doesn't imply anything about where they might be stored at runtime, or whether they might be protected at runtime.

In practice, the compiler may choose to put constants in the program section of the executable, which may be write-protected by the memory-management unit (if it exists). Alternatively, the compiler may fold the constants directly into the code, so that they don't even exist as addressable locations.

Alternatively, it may do none of these things.

Oli Charlesworth
A: 

The constness of a variable is enforced by the compiler and not the underlying machine.

The compiler endeavours to ensure that the variable is not allowed to be changed by any other code after it has been initialized.

Adrian Regan
+1  A: 

In C++, const, rarely has anything to do with hardware. It is mostly a way to tell the compiler that certain kinds of access should result in a compiler error.

The only exception is static const variables of primitive or POD type, which are usually linked into a read-only section in the executable image, and will trigger some kind of page fault if you cast away const-ness and try to modify one of them.

Marcelo Cantos
+2  A: 

"const" does not necessarily mean the storage is read-only. It is a declaration that the C++ program will not change it (and hence that the compiler should reject any attempt to do so). It doesn't mean the value will not change.

It's quite legitimate for a variable to be "const volatile" (the program won't change it, but it might change at any time). A read-only hardware port might well be such a beast, for example.

So at the "lower levels of the machine", nothing needs to be done. The memory is what it is, and the application programmer needs to declare stuff correctly..

Paul