Erroneous Comparisons of Negative Characters

James W. McKelvey mckelvey@maskull.com
Sun May 2 03:05:00 GMT 2004


When chars are implemented as signed, characters with negative values compare 
properly as individual chars, but improperly when part of a char array or 
std::string -- they compare as unsigned. The problem appears to be that the 
specialization of std::char_traits<char> uses memcmp. This is observed on an 
Alpha running RH 7.1 and gcc version 3.5.0 20040207.

Specifically, std::char_traits<char>::compare is inconsistent with 
std::char_traits<char>::lt, which affects std::string (which is just 
std::basic_string<char>.) The problem also affects strcmp, strncmp, and 
strcoll.

The attached program demonstrates the problem.

I post this because I want to be sure that there isn't some bizarre reason 
that this behavior is intended before I file a bug report; or maybe I am 
doing something wrong.

Result of running test program, with my analysis:

122      Expected character value of 'z'.
-64      Expected value of signed character '\0300'
192      Expected value of unsigned character '\0300'
-64      Shows that chars are signed

SC 1    Expected character comparison as signed char
UC 0    Expected character comparison as unsigned char
CH 1    Expected character comparison as char (signed)
SV 1    Demonstrates that std::string::value_type is signed
ST 0    Error: std::string of length 1 does not compare the same as CH
BS 1    std::basic_string<signed char> compares as expected
BU 0    std::basic_string<unsigned char> compares as expected
BC 0    Error: Same as ST, as expected (std::basic_string<char>)
TS 1    std::char_traits<signed char> compares signed char * as expected
TU 0    std::char_traits<signed char> compares unsigned char * as expected
TC 0    Error: std::char_traits<char>, char * does not compare properly
LS 1    std::char_traits<signed char> compares signed char as expected
LU 0    std::char_traits<unsigned char> compares unsigned char as expected
LC 1    std::char_traits<char> compares char as expected
          (Note: inconsistent with TC)
MC 0   std::memcmp is comparing as unsigned (I guess that's OK)
SC 0    Error: std::strcmp is comparing as unsigned
SN 0    Error: std::strncmp is comparing as unsigned
SL 0     Error: std::strcoll is comparing as unsigned

Comments?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: zzz.cc
Type: text/x-c
Size: 2876 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20040502/5ddc50f4/attachment.bin>


More information about the Gcc-help mailing list