Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Program to sort three integers Date: Fri, 06 Nov 2015 12:52:41 -0800 Organization: None to speak of Lines: 50 Message-ID: References: <8dcd1ed2-2734-4cff-b013-d713a33100ed@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="5899"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/G69k0Zai1ndDCshl4mviP" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:dKwTez94LgRaVNtwRa06RBlJnWg= sha1:+4FVSt4U+EewSypqwvbTmn42cdM= Xref: csiph.com comp.lang.c:75182 Bartc writes: > On 06/11/2015 19:36, Keith Thompson wrote: >> void sort2(int *x, int *y) { >> if (*x > *y) { >> const int old_x = *x; >> *x = *y; >> *y = old_x; >> } >> } > > I'd question the benefit of using 'const' here. Actually I found it > distracted from the code (the out-of-sequence declaration, which also > renders the first assignment out of alignment, doesn't help). Noted. > A variable has value stored it it, then that value is used just once, > two lines later, and the function returns. What would happen without the > const? One thing that *could* happen is that if I mixed up the assignments and assigned a new value to old_x, the compiler would catch it for me. I like to define things as const *unless* I'm going to be modifying them. If I follow that consistently, then an object defined without const stands out and implies that I'm going to want to modify it. I understand not everyone follows that convention. > And why not also write: > > void sort2(int * const x, int * const y) ? Good question. If I were to be 100% consistent then yes, I'd define the parameters as const. There are several reasons I don't bother, none of them really good. One is that I like to keep parameter declarations in function declarations and definitions consistent, and the const is meaningless in a declaration. Another is that I stumble briefly over the ordering of "*" and "const", so omitting "const" makes it a little easier to read. (As I've probably mentioned too many times, in my dream language objects would be read-only by default, and you'd have to add a keyword if you want to be able to change them after initialization.) -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"