为什么首先允许指针从非常量到 const 的隐式转换?

Why is an implicit conversion from non-const to const allowed for pointers in the first place?

我理解从 non-constconst 的隐式转换在处理值时并不危险,例如:

int mutable = 5;
const int immutable = mutable;

然而,当使用指针时,我可以做如下事情:

int some_number = 5;
int *mutable = &some_number;
const int *immutable = mutable;    // <= Legal, but isn't it dangerous?

// Let's try to break const
printf("%d\n", *immutable);        // Prints 5
mutable[0] = 10;
printf("%d\n", *immutable);        // Prints 10

顺便说一下,对于双指针,这是不允许的(至少你会得到一个警告)!请参阅 this 问题及其中的参考资料。

来自 the C11 standard (draft N1570):

6.7.3 Type qualifiers

Syntax

  1. type-qualifier:
    const
    restrict
    volatile
    _Atomic

[...]

Semantics:

  1. The properties associated with qualified types are meaningful only for expressions that are lvalues.

[...]

EXAMPLE 1

An object declared

extern const volatile int real_time_clock;

may be modifiable by hardware, but cannot be assigned to, incremented, or decremented.

简单来说:

const 并不意味着值永远不会改变。只代表不准改1.

对于被调用者const是限制,不是承诺。
然而,对于 来电者 来说,它 一个承诺。将 const 指针传递给函数,您可以安全地假设该函数不会更改您的数据 2,因此 "making a promise to you".


1 ...通过带有 const 限定符的标识符。
2 ...通过传递给它的 const 参数。