const and pointers in C

后端 未结 5 2110
星月不相逢
星月不相逢 2021-02-18 17:47

The use of const with a pointer can make the pointee not modifiable by dereferencing it using the pointer in question. But why neither can I modify what the pointer is not direc

5条回答
  •  被撕碎了的回忆
    2021-02-18 18:27

    Although other answers explain the technicalities of why it doesn't work, I'd like to offer a more general reason: it's the only thing that makes sense.

    The problem is that there is no general way for the compiler to decide whether p + something is the same as p or not, because something can be arbitrarily complex. A rule like "Values pointed to by p and p + 0 are unmodifiable, but other values can still be modified" cannot be checked at compile time: imagine if you wrote:

    *(p + very complex expression) = ...
    

    should your compiler be able to figure out if very complex expression is zero? What about

    int s;
    scanf("%d", &s);
    *(p + s) = ...
    

    What should the compiler do in that case?

    The only reasonable choice here was to make any value accessed through p unmodifiable.

提交回复
热议问题