Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

c++ - Comparison signed and unsigned char

It seems so strange. I found misunderstanding. I use gcc with char as signed char. I always thought that in comparison expressions(and other expressions) signed value converts to unsigned if necessary.

int a = -4;
unsigned int b = a;
std::cout << (b == a) << std::endl; // writes 1, Ok

but the problem is that

char a = -4;
unsigned char b = a;
std::cout << (b == a) << std::endl; // writes 0

what is the magic in comparison operator if it's not just bitwise?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the C++ Standard

6 If both operands are of arithmetic or enumeration type, the usual arithmetic conversions are performed on both operands; each of the operators shall yield true if the specified relationship is true and false if it is false.

So in this expression

b == a

of the example

char a = -4;
unsigned char b = -a;
std::cout << (b == a) << std::endl; // writes 0

the both operands are converted to type int. As the result signed char propagets its signed bit and two values become unequal.

To demonstrate the effect try to run this simple example

{
    char a = -4;
    unsigned char b = -a;

    std::cout << std::hex << "a = " << ( int )a << "'b = " << ( int )b << std::endl;

    if ( b > a ) std::cout << "b is greater than a, that is b is positive and a is negative
";
}

The output is

a = fffffffc'   'b = 4
b is greater than a, that is b is positive and a is negative

Edit: Only now I have seen that definitions of the variables have to look as

    char a = -4;
    unsigned char b = a;

that is the minus in the definition of b ahould not be present.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...