Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!border3.nntp.dca.giganews.com!Xl.tags.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!local2.nntp.dca.giganews.com!nntp.earthlink.com!news.earthlink.com.POSTED!not-for-mail NNTP-Posting-Date: Mon, 23 May 2011 22:27:42 -0500 Message-ID: <4DDB25AA.35DF@mindspring.com> Date: Mon, 23 May 2011 23:27:38 -0400 From: pete Reply-To: pfiland@mindspring.com Organization: PF X-Mailer: Mozilla 3.04Gold (WinNT; I) MIME-Version: 1.0 Newsgroups: comp.lang.c Subject: Re: strcmp implementation with unsigned conversion References: <7e64bfe8-e03c-4052-919b-4cd13393ef3c@q14g2000prh.googlegroups.com> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Lines: 66 X-Usenet-Provider: http://www.giganews.com NNTP-Posting-Host: 4.154.219.57 X-Trace: sv3-539gJn9yEQWacDDpLZ+a3jP/yoDSE97uSEy/MO8fOlMsG/0MBYwbgJPua4WN74pNwZvxHpdSFhH3YM7!nv7zeXZZdX894JLuzW8jYC1KsAnhq7Aml/yMi5bqrv6eb2AdpqUPxRpyHjo7LThO+RNgU4/fzyFK!FJrla/xMSw== X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 X-Original-Bytes: 2804 Xref: x330-a1.tempe.blueboxinc.net comp.lang.c:4656 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