If you have "const int x" (as a local variable, global variable, or function parameter) then there is no valid way to modify x's value. But if you have "const int* y" (as a local variable, global variable, or function parameter), you can always cast away const and mutate as long as the original variable (the one "y" points to) wasn't declared const.
No, it's not. That's the whole point why compiler can't optimize it away. You can often see ("char *") casts from static "strings" in legacy APIs and libraries calls, because original authors didn't know or didn't care how to use const correctly (or at all). I, personally, use const a lot throughout my C code, when you get it, it makes debugging so much easier.
if a variable is declared const, casting away const-ness is undefined
is that not true?
So if you cast away constness to conform to some API and then read the value, everything is fine (aside from questionable API design, of course). Modifying the value is another story, though.
P.S. if you downvoted to disagree with this (on my parent post), please provide an opposite example, because as a C programmer, I would really be interested to be proven wrong on this matter.
It seems highly non-intuitive to me that casting away constness works differently depending on whether the variable was defined const or not, but if that's the rules, that's the rules.
It's completely valid to use a non-const pointer to a const variable for reading that variable (this is actually quite common when interacting with libraries that are not const-correct). Undefined behavior only occurs when the const variable is being modified.
This is important because older libs that ignore (or abuse) const will often do read-only access to a char* or something. A nice example is that POSIX defines
int execv(const char *path, char *const argv[]);
That definition takes a constant pointer to variable chars! Worse, some people use the same signature for `main()` and also for libraries that parse `argv`. But none of them are actually allowed to vary those chars under Unix.