by moonchild · 5y ago · 0 comments
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.
It is not about enabling compiler optimisations but about preserving invariants.
void mutate(const int *x) {
*(int*)x = 5;
}
int main() {
int a;
mutate(&a); // ok
const int b;
mutate(&b); // undefined behaviour
}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.