Home >Backend Development >C++ >Why is Converting a Pointer-to-Pointer-to-Non-const to a Pointer-to-Pointer-to-const Prohibited in C ?
Pointer Dereferencing: Why the Conversion to 'pointer to pointer to const' is Prohibited
In C , it is permissible to convert a pointer-to-non-const to a pointer-to-const. However, the conversion from a pointer-to-pointer-to-non-const to a pointer-to-pointer-to-const is not allowed. This raises the question: why?
To understand the reasoning behind this restriction, we must consider pointer dereferencing. When dereferencing a pointer-to-pointer, it represents accessing the value pointed to by the innermost pointer. For instance, consider the code:
Here, **pptr is equivalent to *ptr, which is simply the value i.
However, if we were to allow the conversion to a pointer-to-pointer-to-const, a similar dereferencing operation would yield a constant value. This would introduce a inconsistency, breaking the immutability of const pointers. For example:
Here, s2 is a const pointer, meaning it cannot point to anything else. However, if ps were allowed, we could potentially dereference it to get a, then modify the value of a, effectively altering the value pointed to by s2, which is forbidden.
Therefore, to maintain the integrity of const pointers, the language prohibits the conversion from a pointer-to-pointer-to-non-const to a pointer-to-pointer-to-const. This ensures that the immutability of const pointers is preserved, preventing unintentional modifications to constant values.
The above is the detailed content of Why is Converting a Pointer-to-Pointer-to-Non-const to a Pointer-to-Pointer-to-const Prohibited in C ?. For more information, please follow other related articles on the PHP Chinese website!