C++ – Conversion from unsigned to signed type safety

cunsigned

Is it safe to convert, say, from an unsigned char * to a signed char * (or just a char *?

Best Answer

The access is well-defined, you are allowed to access an object through a pointer to signed or unsigned type corresponding to the dynamic type of the object (3.10/15).

Additionally, signed char is guaranteed not to have any trap values and as such you can safely read through the signed char pointer no matter what the value of the original unsigned char object was.

You can, of course, expect that the values you read through one pointer will be different from the values you read through the other one.

Edit: regarding sellibitze's comment, this is what 3.9.1/1 says.

A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.9); that is, they have the same object representation. For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the value representation represent numbers.

So indeed it seems that signed char may have trap values. Nice catch!