Today I faced an interview in which one question was very tricky for me. Interviewer said \"how to make constant able to change its value?\"
I replied \"using point
If he said this is fine, then he was wrong: trying to modify a constant object gives undefined behaviour. In practice, one of three things might happen:
The language doesn't define any run-time properties of const
objects; just compile-time checks that you don't accidentally modify them.
Perhaps your interviewer was referring to a "physical" property:
If the variable is located in the (read-only) code-section of the program, then any attempt to change it will result with a runtime exception.
For example, the following piece of code will most likely be compiled with string "abc"
allocated in the code-section:
char* str = "abc";
str[1] = 'x';
Any attempt to write into that string will result with a runtime exception.
In order to prevent this from happening (by generating a compile-time error instead), you should declare str
as const
.
Here is a more "real-life" example:
I've got a program built for STM32 (an ARM-based cortex).
When I load it into the CPU through JTAG, the code-section is burned into EPROM, and the data-section is written into RAM.
The code-section includes all the code, as well as all the const
variables.
The data-section includes all the global and/or static variables.
Any attempt to convert a const
pointer to a "regular" pointer and then use it in order to write into memory, immediately leads to a memory access violation, as the CPU attempts to perform a RAM-Write operation into an EPROM address.
I would think that the interviewer was expecting you to say const_cast<>() which can make a constant declared variable changeable in code.