Sujet : Re: So You Think You Can Const?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 08. Jan 2025, 21:08:21
Autres entêtes
Organisation : None to speak of
Message-ID : <877c75rruy.fsf@nosuchdomain.example.com>
References : 1 2
User-Agent : Gnus/5.13 (Gnus v5.13)
David Brown <
david.brown@hesbynett.no> writes:
[...]
int v = 123; // Non-const object definition
const int * cp = &v; // Const pointer to non-const data
cp isn't a const pointer, i.e., it's not a pointer object whose value
cannot be changed. It's a pointer to const, specifically a pointer to
const int. You could (and arguably should) make the pointer itself
const by defining:
const int *const cp = &v;
v, as you point out, is a non-const object. *cp provides access to that
object in a way that forbids changing the target via that pointer.
int * p = (int *) cp; // Cast to non-const pointer
*p = 456; // Change the target data
You could also write:
*(int*)p = 456;
[...]
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */