Does `const T *restrict` guarantee the object pointed-to isn’t modified?

后端 未结 4 1280
南笙
南笙 2020-12-16 19:32

Consider the following code:

void doesnt_modify(const int *);

int foo(int *n) {
    *n = 42;
    doesnt_modify(n);
    return *n;
}

where

4条回答
  •  醉梦人生
    2020-12-16 20:12

    Generally, restrict means that the pointer is not aliased (i.e. only it or a pointer derived from it can be used to access the pointed-to object).

    With const, this means that the pointed-to object cannot be modified by well-formed code.

    There is, however, nothing to stop the programmer breaking the rules using an explicit type conversion to remove the constness. Then the compiler (having been beaten into submission by the programmer) will permit an attempt to modify the pointed-to object without any complaint. This, strictly speaking, results in undefined behaviour so any result imaginable is then permitted including - possibly - modifying the pointed-to object.

提交回复
热议问题