home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
- From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
- Subject: Re: HIgher problems at hand. HELP!
- Message-ID: <9220806.7841@mulga.cs.mu.OZ.AU>
- Sender: news@cs.mu.OZ.AU
- Organization: Computer Science, University of Melbourne, Australia
- References: <Brv6oD.Dq5@usenet.ucs.indiana.edu> <1992Jul25.142216.5636@druid.uucp>
- Date: Sat, 25 Jul 1992 20:29:41 GMT
- Lines: 57
-
- darcy@druid.uucp (D'Arcy J.M. Cain) writes:
-
- >/*
- > * strstr - find first occurrence of wanted in s
- > *
- > * based on code by Henry Spencer
- > * modified for ANSI by D'Arcy J.M. Cain
- > */
- >
- >/* The following define required for full checking. The problem is that */
- >/* the function has to ultimately assign a const char * to the return */
- >/* value which has to be char *. The answer is to drop the use of */
- >/* const in this module and trust the code to do the right thing */
- >#define const
-
- Yuck!
- Do *not* #define keywords unless you have absolutely no alternative.
-
- >#include <string.h>
-
- Now what happens if string.h happens to contain
- const CHAR_BIT = 8;
- or some such?
-
- >char *strstr(const char *s, const char *wanted)
-
- This is a *different* prototype to the externally visible one, since
- this one doesn't include "const". An implementation is well within it's
- rights to give you a warning at link time, and probably even an error.
-
- >{
- > size_t len;
- > char firstc;
- >
- > /*
- > * The odd placement of the two tests is so "" is findable.
- > * Also, we inline the first char for speed.
- > */
- > firstc = *wanted;
- > len = strlen(wanted);
- >
- > while (*s != firstc || strncmp(s, wanted, len) != 0)
- > if (*s++ == '\0')
- > return(NULL);
- >
- > return(s);
- >}
-
- The solution to the const problem is just to put a cast in the final return
- statement:
- return (const char *) s;
-
- --
- Fergus Henderson fjh@munta.cs.mu.OZ.AU
- This .signature VIRUS is a self-referential statement that is true - but
- you will only be able to consistently believe it if you copy it to your own
- .signature file!
-