Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: EXIT_SUCCESS Date: Tue, 26 Jul 2016 08:24:25 -0700 Organization: None to speak of Lines: 51 Message-ID: References: <87r3b4xdsa.fsf@gmail.com> <6f1e2608-eac3-49ea-a5f4-0fdc746b2942@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="30083"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/2LfDTGb4/xOFXpf1nZEJf" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:GO4Rh8rpBqTDY89+80ceGe60pm8= sha1:SDLJdGmCBdJ9qtAEtavCuOoQYfk= Xref: csiph.com comp.lang.c:91089 David Brown writes: > On 25/07/16 17:46, Keith Thompson wrote: >> jgh@mdfs.net writes: >>> Keith Thompson wrote: >>>> A better solution is: >>>> if (a == 0) result = "zero"; >>>> else if (a == 1) result = "one"; >>>> else if (a == 2) result = "two"; >>>> else if (a == 3) result = "three"; >>>> else result = "four"; >>>> return result; >>> >>> If you want to do multiple ifs like that, I prefer to do: >>> result = "four"; // default >>> if (a == 0) result = "zero"; >>> if (a == 1) result = "one"; >>> if (a == 2) result = "two"; >>> if (a == 3) result = "three"; >>> return result; >>> >>> jgh >> >> Why do you omit the "else"s? > > Presumably the else's were omitted because they are not necessary, and > perhaps also because in many coding standards they would require > brackets to added. The else's don't make the code any clearer to the > reader, and are unlikely to make any difference to a compiler's code > generation (assuming at least basic optimisation). They might not be necessary in this particular case, but when I read the code I have to verify that no more than one of the conditions can be true. In a more complicated example, that could be difficult. I doubt that a coding standard would require curly braces with "else" but not require them without it. And if it did, the answer would be to add the braces. (In any case, thanks for your response, but I asked why jgh ommitted the "else"s.) >> Of course in this specific case a switch statement would be clearer >> (and, less importantly, faster), but I presume the example is meant >> as a more general illustration, covering cases where "switch" would >> not work. -- 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"