which property of a constant makes it not changable?

后端 未结 3 2059
闹比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条回答
  •  梦毁少年i
    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.

提交回复
热议问题