Is it safe to cast an unsigned char* to char*, and treat the dereferenced pointer as if it really points to a char?

后端 未结 2 1157
终归单人心
终归单人心 2020-12-28 16:35

Following the question titled Warning generated due wrong strcmp parameter handling, there seems to be some questions regarding what the Standard actually guarantees regardi

2条回答
  •  攒了一身酷
    2020-12-28 17:06

    strcmp (buf1, reinterpret_cast (buf2));
    

    This looks fine,

    It is. strcmp takes const char * parameters, but internally converts them to const unsigned char * (if required), so that even if char is signed and two distinct bytes can compare equal when viewing them as char, they will still compare different when viewing them with strcmp.

    C99:

    7.21 String handling

    7.21.1 String function conventions

    3 For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value).

    That said,

    but does the Standard guarantee that the (1) will always yield true?

    char unsigned * p1 = ...;
    char          * p2 = reinterpret_cast (p1);
    
    *p1 == *p2; // (1)
    

    What you wrote is not guaranteed.

    Take a common implementation, with signed char, 8-bit bytes using two's complement representation. If *p1 is UCHAR_MAX, then *p2 == -1, and *p1 == *p2 will be false because the promotion to int gives them different values.

    If you meant either (char) *p1 == *p2, or *p1 == (unsigned char) *p2, then those are still not guaranteed, so you do need to make sure that if you copy from an array of char to an array of unsigned char, you don't include such a conversion.

提交回复
热议问题