Workaround to modify a const value without the protection from @constCast, yet the test expects initialization value

The type is small, it is const with a comptime known value; so the compiler can avoid loading it from memory, instead embedding the known value into the instructions as an optimisation.

The error is your code not preserving the constness of the pointer, which then allows it to modify the value which is illegal behaviour.

What is surprising is that, despite being const and comptime known, a is for some reason not in read only memory, or even in memory at all. Either of those would crash your program when trying to write to it. That could certainly be fixed to make this programmer error more obvious.

Coincidently there was a similar post today How to explain the behavior of modifying the value referenced by the result of @constCast? - #5 by npc1054657282

Btw @constCast offers no protection against this, as shown by the linked post.
zig believes you when you lie to it, because it has no way to know if you’re lying or not.

3 Likes