which property of a constant makes it not changable?

后端 未结 3 2044
闹比i
闹比i 2021-01-03 01:39

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

相关标签:
3条回答
  • 2021-01-03 02:21

    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 constant variable behaves just like a normal object, and you see its value change;
    • It's stored in unwritable memory, and the program crashes with an access violation;
    • Each use of it is replaced with a hard-coded value, and you don't see it change.

    The language doesn't define any run-time properties of const objects; just compile-time checks that you don't accidentally modify them.

    0 讨论(0)
  • 2021-01-03 02:27

    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.

    0 讨论(0)
  • 2021-01-03 02:29

    I would think that the interviewer was expecting you to say const_cast<>() which can make a constant declared variable changeable in code.

    0 讨论(0)
提交回复
热议问题