3 ms·
> With a const pointer the callee can not mutate the pointee. But it can still be mutated from the outside That's incorrect. In c semantics, at least, it is l
by moonchild 5y ago
> With a const pointer the callee can not mutate the pointee. But it can still be mutated from the outside
That's incorrect. In c semantics, at least, it is legal to take a pointer to non-const, cast it to a pointer to const, pass it back, and mutate the object pointed to. It is only illegal to mutate if the pointer actually points to const memory.
Which means that, in a general sense, if you're given a const pointer, since you can't know if it actually points at const memory, you shouldn't mutate through it. But if you're handing out const pointers to non-const memory, you shouldn't count on the memory not being changed through those pointers.
IOW const is all but useless in c (except as a declaration of intent).
> An ABI like this would probably be much more complex to implement for a small gain
Why? Mechanically, it's almost the same as the ms/arm/riscv abi, except that a copy is made by the callee rather than the caller.
- gpderetta 5y agoConst matters to the caller, if it calls a function that takes a pointer to const it can generally reasonably expect that the object wont be changed. It is not about enabling compiler optimisations but about preserving invariants.
- TwoBit 5y agoAre you saying that in C a callee can cast a const pointer to non-const and write to it and that's sanctioned by the Standard?
- moonchild 5y agoYes, as long as the original pointer was to a non-const location. That is: void mutate(const int *x) { *(int*)x = 5; } int main() { int a; mutate(&a); // ok const int b; mutate(&b); // undefined behaviour }
- TwoBit 5y ago> Yes, as long as the original pointer was to a non-const location. So then actually no - it's not guaranteed to be portable. That non-const location qualification of course means portable code cannot just cast const pointers to non-const.