C — Accessing a non-const through const declaration

前端 未结 5 1091
轮回少年
轮回少年 2020-11-30 13:15

Is accessing a non-const object through a const declaration allowed by the C standard? E.g. is the following code guaranteed to compile and output

5条回答
  •  难免孤独
    2020-11-30 13:38

    In the B translation unit, const would only prohibit modifying the a variable within the B translation unit itself.

    Modifications of that value from outside (other translation units) will reflect on the value you see in B.

    This is more of a linker issue than a language issue. The linker is free to frown upon the differing qualifications of the a symbol (if there is such information in the object files) when merging the compiled translation units.

    Note, however, that if it's the other way around (const int a = 23 in A and extern int a in B), you would likely encounter a memory access violation in case of attempting to modify a from B, since a could be placed in a read-only area of the process, usually mapped directly from the .rodata section of the executable.

提交回复
热议问题