Path: ...!weretis.net!feeder9.news.weretis.net!news.quux.org!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Julio Di Egidio Newsgroups: comp.lang.c Subject: Re: So You Think You Can Const? Date: Wed, 15 Jan 2025 13:53:22 +0100 Organization: A noiseless patient Spider Lines: 65 Message-ID: References: <87frlt5yym.fsf@bsb.me.uk> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Wed, 15 Jan 2025 13:53:23 +0100 (CET) Injection-Info: dont-email.me; posting-host="2563c1350cfe2ddd1cd2f0f3cf044725"; logging-data="3106880"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+howUiLANqUizja3LBIbacLXsGRYq6CpU=" User-Agent: Mozilla Thunderbird Cancel-Lock: sha1:pDqFnrMLZ4N1VSyjm+WAcJANnig= Content-Language: en-GB In-Reply-To: Bytes: 3397 On 08/01/2025 13:25, David Brown wrote: > On 08/01/2025 12:25, Ben Bacarisse wrote: >> David Brown writes: >> >>> Suppose you have : >>> >>>     int v = 123;        // Non-const object definition >>>     const int * cp = &v;    // Const pointer to non-const data >>>     int * p = (int *) cp;    // Cast to non-const pointer >>>     *p = 456;        // Change the target data >>> >>> This is allowed, because the original object definition was not a const >>> definition. >>> >>> However, with this: >>> >>>     int v = 123;        // Const object definition > > Correction: >     const int v = 123; > >>>     const int * cp = &v;    // Const pointer to const data >>>     int * p = (int *) cp;    // Cast to non-const pointer >>>     *p = 456;        // Undefined behaviour >> >> I think missed out the crucial "const" on the first line of the second >> example!  It's always the way. > > Fortunately, Usenet is a self-correcting medium :-)  Thanks for pointing > out that mistake, and I hope the OP sees your correction before getting > confused by my copy-pasta error. LOOK AT THESE TWO PIECES OF NAZI-RETARDED SPAMMING SHIT. -Julio >>> You can make the pointer to non-const, but trying to change an object >>> that >>> was /defined/ as const is undefined behaviour (even if it was not >>> placed in >>> read-only memory). >>> >>> When you use dynamic memory, however, you are not defining an object >>> in the >>> same way.  If you write : >>> >>>     const int * cp = malloc(sizeof(int)); >> >> I prefer >> >>      const int *cp = malloc(sizeof *cp); >> > > That's a common preference.  Personally, I prefer the former - I think > it makes it clearer that we are allocating space for an int.  Hopefully > the OP will hang around this group and we'll get a chance to give advice > and suggestions on many different aspects of C programming. > >>> you are defining the object "p" as a pointer to type "const int" - >>> but you >>> are not defining a const int.  You can cast "cp" to "int *" and use that >>> new pointer to change the value. >> >