Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the 'const' keyword work?

Tags:

c++

constants

Using const prevents a variable from being changed. Easy enough.

const int x = 5;

x = 6; //not allowed!

But how is this actually being implemented?

Is it just a compiler rule? Or is there something happening at the machine code level that distinguishes between const and non-const variables?

edit: my question is distinct from this since that question was only asking about how the compiler keeps track of what is const and what isn't. My question is not this. My question is about the actual machine-code-level meaning of const, if there is one (seems like it might just be a compiler hint). At any rate, just take a look at how the answers to my question and the answers to the linked question are different. That should give you a hint that this isn't a duplicate.

edit: The 'duplicate' question about accessing members in a derived class is not duplicate. Different question, different answer.

like image 291
Adam Avatar asked Dec 24 '22 04:12

Adam


1 Answers

But how is this actually being implemented?

The language specification leaves this to the discretion of the implementation, as long as the compiler ensures, that the immutability semantics enforces by this are not violated by the program source code (i.e. assignment to a const object gives a compilation error and discarding a const specifier yields implementation defined behavior).

The standard does not require runtime checks. However if an implementation can do/enforce runtime checks, it's perfectly legal to have them.

For example global/static scope const values may be placed in a read-only memory region, like say, ROM in a microcontroller, or pages mapped read-only in an OS with virtual memory. Most executable formats specify a special section for read-only data (like e.g. .rodata in ELF), which will mapped read-only, and attempting to modify the contents inside that memory region will be caught by the operating system and result in a program exception.

like image 116
datenwolf Avatar answered Dec 28 '22 07:12

datenwolf