问题描述
这似乎很奇怪.我发现误会了.我使用带有字符的gcc作为签名字符.我一直认为,在比较表达式(和其他表达式)中,如有必要,带符号的值会转换为无符号的值.
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
但是问题在于
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?
推荐答案
根据C ++标准
所以在这个表达式中
b == a
示例
char a = -4;
unsigned char b = -a;
std::cout << (b == a) << std::endl; // writes 0
两个操作数都转换为类型int
.结果,带符号的char扩展了其带符号的位,并且两个值不相等.
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 << "'\tb = " << ( int )b << std::endl;
if ( b > a ) std::cout << "b is greater than a, that is b is positive and a is negative\n";
}
输出为
a = fffffffc' 'b = 4
b is greater than a, that is b is positive and a is negative
直到现在我才看到变量的定义必须看起来像
Only now I have seen that definitions of the variables have to look as
char a = -4;
unsigned char b = a;
那是b定义的负号.
这篇关于比较有符号和无符号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!