This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

String comparison in std::string.h

Hi, while looking at the string.h coming with the c6000_7.4.2 compiler tools I came across the following string comparison function:

/********************************************************************************/

int strcmp ( register const char * string1 , register const char * string2 )
{

    register int c1, res;
    for (;;)
    {

         c1  = (unsigned char)*string1++;
         res = c1 - (unsigned char)*string2++;

         if (c1 == 0 || res != 0) break;
   }

    return res;
}

/********************************************************************************/

Could someone explain why are the (unsigned char) casts necessary ?!

Thanks a lot,

Todor

  • For purposes of comparison, characters have no sign.  That is, a character with value 0xA9 should be considered greater than a character with value 0x62.  This unsigned char cast insures, when the characters are converted to the wider int type, the upper bits are set to 0, and not sign extension (i.e. whatever the MSB is).  The ANSI specification is actually unclear on this detail of strcmp, but this unsigned comparison behavior has become the de facto standard.

    Thanks and regards,

    -George

  • Very fast and clear answer. Thanks a lot.

    Todor