Re: '\0' ?

From: Al Bowers (xabowers_at_rapidsys.com)
Date: 10/31/04


Date: Sun, 31 Oct 2004 08:59:12 -0500


Skybuck Flying wrote:

> Hi,
>
> I have a question about \0
>
> This is the implementation of strcmp in glibc.
>
> Which is probably the same on many other compilers/libraries.

This implementation appears suspicious. Comment of the suspicious
code is below.
>
> My question is about this:
>
> if (c1 == '\0')
>
> What does '\0' mean ?
>
> Is that a null terminated character ?
>
Yes, it is the nul-terminating character which is required
to terminate all strings. THe Standard's definition of strcmp
does not mention the nul character but speaks in terms of
strings. Function strncmp is a different story.

> Does that mean strcmp stops comparing as soon as it encounters a null
> terminated character ?

Yes.

>
>
> #include <string.h>
> #include <memcopy.h>
>
> #undef strcmp
>
> /* Compare S1 and S2, returning less than, equal to or
> greater than zero if S1 is lexicographically less than,
> equal to or greater than S2. */
> int
> strcmp (p1, p2)
> const char *p1;
> const char *p2;
> {
> register const unsigned char *s1 = (const unsigned char *) p1;
> register const unsigned char *s2 = (const unsigned char *) p2;
> unsigned reg_char c1, c2;
>
> do
> {
> c1 = (unsigned char) *s1++;
> c2 = (unsigned char) *s2++;
> if (c1 == '\0')
> return c1 - c2;

if stored in s1 is '\0' then c1 would equal 0. c2 may be some
unsigned value, for example, 97.
So you have, for example, (unsigned)0 - (unsigned)97. Is is
possible or not possilbe for this to return a negative value
when converted to type int and returned from the function?

> }
> while (c1 == c2);
>
> return c1 - c2;
> }
> libc_hidden_builtin_def (strcmp)
>

-- 
Al Bowers
Tampa, Fl USA
mailto: xabowers@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Quantcast