Path: csiph.com!news.mixmin.net!eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: Do you insist on const-correctness? Date: Sun, 17 Sep 2023 17:17:36 -0700 Organization: A noiseless patient Spider Lines: 53 Message-ID: <86a5tkmj1b.fsf@linuxsc.com> References: <20230918012105.b9fb2c36e93542dddb654b1f@gmail.moc> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: dont-email.me; posting-host="eea9b3fa2266531b102f184a126e7979"; logging-data="649064"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+ABVsfqvpUkma1kCJAxkWXoHuho15+uqo=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:dqzjt9ofb9pnPMdOUqJYBhJYOWw= sha1:TVR2c1z4J49c+o4CoRl3QCcGuHs= Xref: csiph.com comp.lang.c:175832 Anton Shepelev writes: > This is my function for setting the length of a dynamic > array: > > void* a_setlen( void * a, unsigned len ) > { unsigned newcap; > struct meta_t *m ; > > m = META ( a ); > m = setlen( m, len ); > if( m != NULL ) a = DATA( m ); > else a = NULL ; > return a; > } > > To allow for a potential reallocation, it returns an updated > pointer to the array. Although it is small, and therefore > easily understandable at a glance as is, I am taught and > told that it smells bad, because of the reuse an input > variable to store the new value to be returned. [...] Is there some reason not to write a shorter and simpler function, such as the function below (please ignore differences in layout style) void* a_setlen( void *a, unsigned n ){ struct meta_t *const m = setlen( META( a ), n ); return m ? DATA( m ) : NULL; } Having the function parameters be const I would say is just personal preference. With a function this short it doesn't make much difference one way or the other. The choice between 'void *a' and 'const void *a' has more substance. If the memory pointed to by 'a' might be written by this function (eg, in the call to setlen()) then 'const' should certainly not be used. If the memory pointed to by 'a' will definitly _not_ be written by this function, then my inclination is to say 'const' should be used if (and maybe only if) it is important to express that property. To say that another way, if it's important for a caller to know that *a will not be modified then 'const void *a' is appropriate, but if *a not being modified is just a happenstance of how the code is written then my vote would be to leave the const off. I'm sure other people have some other opinions as to what is most appropriate here. I am expressing a personal view and also some of the reasoning behind it. I feel strongly that the best choice in such cases is not just "always yes" or "always no".