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.5 required=5.0 tests=BAYES_00,INVALID_MSGID, PP_MIME_FAKE_ASCII_TEXT autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII X-Google-Thread: fac41,9a0ff0bffdf63657 X-Google-Attributes: gidfac41,public X-Google-Thread: 103376,4b06f8f15f01a568 X-Google-Attributes: gid103376,public X-Google-Thread: 1108a1,9a0ff0bffdf63657 X-Google-Attributes: gid1108a1,public X-Google-Thread: f43e6,9a0ff0bffdf63657 X-Google-Attributes: gidf43e6,public From: Matthew Heaney Subject: Re: Software landmines (loops) Date: 1998/09/17 Message-ID: #1/1 X-Deja-AN: 391934805 Sender: matt@mheaney.ni.net References: <6sbuod$fra$1@hirame.wwa.com> <35f51e53.48044143@ <6t6l4n$rep@jbm.nada.kth.se> NNTP-Posting-Date: Wed, 16 Sep 1998 21:02:19 PDT Newsgroups: comp.lang.eiffel,comp.object,comp.software-eng,comp.lang.ada Date: 1998-09-17T00:00:00+00:00 List-Id: jbm@jbm.nada.kth.se (Jonas M�ls�) writes: > 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. > > > > /** str_index > * > * str_index returns a pointer to the first occurrence of > * the given character in the given string. > * If the given character does not occur in the given > * string, str_index returns NULL. > * > * If the given pointer is NULL, the result is undefined. > * > */ > > Here's another idea: char * str_index ( char *s, /* string to search */ char c) /* character to search for */ { for (;;) if (*s == c) return s; else if (*s == '\0') return NULL; else s++; } I don't know if this is typical C code, however. I suspect one would move some of the work up into the for loop declaration: for (; *s != '\0'; s++) if (*s == c) return s; return NULL; An Ada programmer has an easier go of it: function Get_Position (S : String; C : Character) return Natural is begin for Index in S'Range loop if S(Index) = C then return Index; end if; end loop; return 0; end Get_Position;