From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=0.2 required=5.0 tests=BAYES_00,INVALID_MSGID, REPLYTO_WITHOUT_TO_CC autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII X-Google-Thread: 1108a1,9a0ff0bffdf63657 X-Google-Attributes: gid1108a1,public X-Google-Thread: fac41,9a0ff0bffdf63657 X-Google-Attributes: gidfac41,public X-Google-Thread: f43e6,9a0ff0bffdf63657 X-Google-Attributes: gidf43e6,public X-Google-Thread: 103376,4b06f8f15f01a568 X-Google-Attributes: gid103376,public From: Mats Weber Subject: Re: Software landmines (loops) Date: 1998/09/10 Message-ID: <35F74C47.178B2B89@elca-matrix.ch>#1/1 X-Deja-AN: 389627367 Content-Transfer-Encoding: 8bit References: <6sbuod$fra$1@hirame.wwa.com> <35f51e53.48044143@ <6t6l4n$rep@jbm.nada.kth.se> Content-Type: text/plain; charset=iso-8859-1 Organization: Swisscom AG, the blue window Mime-Version: 1.0 Reply-To: Mats.Weber@elca-matrix.ch Newsgroups: comp.lang.eiffel,comp.object,comp.software-eng,comp.lang.ada Date: 1998-09-10T00:00:00+00:00 List-Id: Jonas M�ls� wrote: > Also, I have never encountered a real situation > where I have needed an extra flag in the predicate. > One can actually do fine without them. As an example, > I hereby present to you three variations of str_index. > > The first one strictly exits at the top. The other two > in the middle. The first one is much easier to reason > about, and to understan, IMHO. Anyway, introducing an > extra flag in the predicate is very often a sign of > "patching the loop". Done right, one does not need it. > > > char * > str_index ( > char *s, /* string to search */ > char c) /* character to search for */ > { > while (*s != '\0' && *s != c) > ++s; > > return (*s != c) ? NULL : s; > } The problem with this variant is that you are comparing *s with c once more than in the other two variants. With characters, this is perfectly OK, but this could become a problem if the comparison for equality is more expensive, for instance if you are comparing larger structures or have a more complicated equality function. In fact, you are using "*s == c" as a flag to check why you exited form your loop. Try to reprogram your example doing each comparison only once: you will need a flag if you don't use return in the loop. (I find the other two variants more readable, but that is a matter of taste).