Path: csiph.com!news.mixmin.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: "Catch-23: The New C Standard,Sets the World on Fire" by Terence Kelly with Special Guest Borer Yekai Pan Date: Sun, 09 Apr 2023 12:44:19 -0700 Organization: A noiseless patient Spider Lines: 51 Message-ID: <86mt3g4z8s.fsf@linuxsc.com> References: <87zg7n89zw.fsf@bsb.me.uk> <874jpv84uv.fsf@bsb.me.uk> <20230407042121.909@kylheku.com> <86r0st3zj0.fsf@linuxsc.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: dont-email.me; posting-host="2b6f87d227a563a0c00d2eacd0f30cf4"; logging-data="1942671"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19UYNu35I9j4wY+LJku4OvzsMbHouy69do=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:24kZEZBVs7xT6RX7T/R6qdsF7zw= sha1:mq3jRg0DxVnRrkEIW6jPvNnY3E4= Xref: csiph.com comp.lang.c:169888 jak writes: > Tim Rentsch ha scritto: > >> Kaz Kylheku <864-117-4973@kylheku.com> writes: >> >> [miscellaneous suggestions taken out] >> >>> On 2023-04-06, John Forkosh wrote: >>> >>>> void *realloc0 ( void *ptr, size_t size ) { >>>> void *reptr = NULL; >>>> if ( size < 1 ) { >>>> if ( ptr != NULL ) free(ptr); } >>>> else reptr = realloc(ptr,size); >>>> return ( reptr ); } >>> >>> Consider: >>> >>> return (size == 0) ? free(ptr), NULL : realloc(ptr, size); >>> >>> which avoids multiple returns, variable assignment, and >>> verbiage. >> >> I agree with the general tone of this suggestion. Unfortunately >> however the particular code suggested might not compile (because >> the macro NULL might be #define'd to be 0, which can result in an >> error). Writing the function this way: >> >> void * >> realloc0( void *p, size_t size ){ >> return size == 0 ? free( p ), p = 0 : realloc( p, size ); >> } >> >> is an easy way to avoid that implementation dependency. > > If you absolutely wanted to avoid dependency, perhaps you shouldn't rely > on autocast and use an explicit one instead. The re-written code doesn't have any implementation dependency: it is guaranteed to work in all versions of C back to ANSI C and even K&R C (except of course K&R C doesn't have void or void *, (or size_t?) but the conversion of 0 to any pointer type will work even back in K&R C). Furthermore writing an explicit cast is almost always a bad idea, especially in open code. Writing the expression without a cast gives the compiler a chance to say that the code is wrong, if indeed wrong it is. No diagnostics plus no use of any symbols such as NULL that are implementation-defined means the code will compile successfully everywhere.