Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| Message-ID | <4DDB25AA.35DF@mindspring.com> (permalink) |
|---|---|
| Date | 2011-05-23 23:27 -0400 |
| From | pete <pfiland@mindspring.com> |
| Organization | PF |
| Newsgroups | comp.lang.c |
| Subject | Re: strcmp implementation with unsigned conversion |
| References | <7e64bfe8-e03c-4052-919b-4cd13393ef3c@q14g2000prh.googlegroups.com> |
jianhua wrote:
>
> 1. Why the standard* requires that values
> of the pair of characters be
> "both interpreted as unsigned char"
>
> 2. Can they be both interpreted as other larger types
> eg. int, unsigned int, long, unsigned long
>
> 3. Does "both interpreted as unsigned char" means
>
> this is wrong:
>
> int strcmp(const char *cs, const char *ct)
> {
> while (1) {
> if (*cs != *ct)
> return *cs < *ct ? -1 : 1;
> if (!*cs)
> break;
> cs++, ct++;
> }
> return 0;
> }
>
> but this is right:
>
> /*
> Copyright (C) 1991, 1992 Linus Torvalds
> */
> int strcmp(const char *cs, const char *ct)
> {
> unsigned char c1, c2;
>
> while (1) {
> c1 = *cs++; /*gcc warning: -Wconversion*/
> c2 = *ct++; /*gcc warning: -Wconversion*/
I agree with Eric Sosman that a conversion to unsigned char
is different from being interpreted as unsigned char.
It would be OK this way:
c1 = *(unsigned char *)cs++;
c2 = *(unsigned char *)ct++;
> if (c1 != c2)
> return c1 < c2 ? -1 : 1;
> if (!c1)
> break;
> }
> return 0;
> }
>
> [*] 7.23.4 Comparison functions
> 1 The sign of a nonzero value returned by the comparison functions
> memcmp, strcmp,
> and strncmp is determined by the sign of the difference between the
> values of the first
> pair of characters (both interpreted as unsigned char) that differ in
> the objects being
> compared.
--
pete
Back to comp.lang.c | Previous | Next — Previous in thread | Find similar | Unroll thread
strcmp implementation with unsigned conversion jianhua <jhlicc@gmail.com> - 2011-05-23 11:59 -0700
Re: strcmp implementation with unsigned conversion Keith Thompson <kst-u@mib.org> - 2011-05-23 12:38 -0700
Re: strcmp implementation with unsigned conversion Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-05-23 18:22 -0400
Re: strcmp implementation with unsigned conversion pete <pfiland@mindspring.com> - 2011-05-23 23:27 -0400
csiph-web