Ian Collins said:
On 04/14/10 09:01 AM, candide wrote:
I request your opinion about the following attempt to implement the
standard function strstr. Here is the code :
No, it looks like you are writing strchr.
char *mystrchr(const char *s, int c)
{
while ((unsigned char)*s != (unsigned char)c) {
Why the casts?
Because without them
char buff[LINELEN];
while(get_line_from_post(buff, sizeof(buff))) {
/* detect mangled indents from googoogroups */
char *mangledchars=buff;
while ((mangledchars=mystrchr(mangledchars, 160)) != NULL)
*mangledchars=' ';
}
may fail to fix any non-breaking spaces.
Eh?
If chars are signed, then you'll be comparing char -96 with int 160,
and not find any matches.
Yabbut, it's still wrong. The second argument to strchr()
is an int which is "converted to a char" (7.21.5.2p2), not to
an unsigned char. So the given code behaves differently from
the Standard's description for any char value C and int value I
such that
(C == (char)I) != ((unsigned char)C == (unsigned char)I)
Can such a C,I pair exist? Yes, certainly, if I is less than
CHAR_MIN or greater than CHAR_MAX, because then (char)I is ill-
defined and can produce a peculiar result (6.3.1.3p2). That
peculiar result need not be closely related to the (well-defined)
result of converting to unsigned char, so the two comparisons
could come out differently -- in which case, the fix is to remove
the `unsigned' from both casts and allow the peculiar behavior
to occur. It's what the Standard requires.