J
jianhua
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*/
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.
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*/
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.