Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what makes const at the lower levels of the machine?

Tags:

c++

constants

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?

like image 803
Tony The Lion Avatar asked Oct 28 '10 10:10

Tony The Lion


2 Answers

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.

like image 62
Oliver Charlesworth Avatar answered Oct 06 '22 17:10

Oliver Charlesworth


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.

like image 28
Paul Tomblin Avatar answered Oct 06 '22 16:10

Paul Tomblin