Can “signed char” and “unsigned char” always be transferred to each other without data loss?

In C ++, we can have signed charand unsigned char, which are the same size, but contain different ranges of values.

In the following code:

signed char signedChar = -10;
unsigned char unsignedChar = static_cast<unsigned char>( signedChar );
signedChar = static_cast<signed char>( unsignedChar );

will signed charretain its value regardless of its original value?

+5
source share
4 answers

No, there is no such guarantee. Converting from signed charto unsigned charis correct, since all conversions are integers without subscribers in C ++ (and C). However, the result of this conversion can easily fall outside the bounds of the original signed type (it will happen in your example c -10).

- unsigned char - signed char - , ++ ( C). , .

, "" , signed char . .

+10

, - , . , , , - . , , .

char unsigned char, . unsigned char, 0 255.

( , ), char unsigned char 1 8 . char -128 +127, unsigned char - 0 +255.

, . , . , , , . , Borland ++ Builder 5, signed char test = -1, unsigned char, 255. , .

, , , , . , , , . .

, , , , . , . , , .

, char unsigned char char. , ,

3.9.1 [basic.fundamental]

1 , char) . , . char . . char, char, unsigned char - . A char, char, char (basic.types); . , . , . . , char , char unsigned char; .

+1

AFAIK, this actor will never change the byte, just change his mind.

0
source

My first guess would be "maybe." Have you tried testing this with various inputs?

-1
source

All Articles