Using unsigned char and char

I looked through a lot of strCmp () implementations and found that most pointer implementations are done using unsigned char

My question is: why did "unsigned" use in return, although if we did not use it, we will get the same result (based on the tests I did)?

If I have not used it, will I get the wrong result for some values?

Finally, is there an unsigned char or is it signed by default?

Example 1

int strCmp(const char* s1, const char* s2)
{
    while(*s1 && (*s1 == *s2))
    {
        s1++;
        s2++;
    }    
    return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}

Example 2

int strCmp(const char *S1, const char *S2)
{

  for(; *S1 == *S2; ++S1, ++S2)
    if(*S1 == 0)
      return 0;
  return *(unsigned char *)S1 < *(unsigned char *)S2 ? -1 : 1;
  }
+4
source share
2 answers

My question is why "unsigned" is used instead, although if we did not use it, we will get the same result (based on tests)?

int, , char , - .

: , 8 . 128 -128 , , [0,127], , . unsigned char , 128.

, char ?

, , . unsigned char.

+9

strCmp() , unsigned char

, C int strcmp(const char *s1, const char *s2);, , , unsigned char. , char signed char unsigned char.

, unsigned char C11 §7.24.1 3

// Example that performs the correct compare without a possibility of overflow.
int strCmp(const char* s1, const char* s2) {
  const unsigned char *u1 = (const unsigned char *) s1;
  const unsigned char *u2 = (const unsigned char *) s2;
  while((*u1 == *u2) && *u1) {
    u1++;
    u2++;
  }    
  return (*u1 > *u2) - (*u1 < *u2);
}

, unsigned char == range unsigned.

return *(const unsigned char*)s1 - *(const unsigned char*)s2;
+1

Source: https://habr.com/ru/post/1695770/


All Articles