gpt4 book ai didi

c++ - 比较有符号和无符号字符

转载 作者:搜寻专家 更新时间:2023-10-31 00:36:45 26 4
gpt4 key购买 nike

看起来很奇怪。我发现了误会。我将 gcc 与 char 一起用作带符号的 char。我一直认为在比较表达式(和其他表达式)中,有符号值会在必要时转换为无符号值。

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

如果不只是按位,比较运算符有什么魔力?

最佳答案

根据C++标准

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.

所以在这个表达式中

b == a

例子

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

两个操作数都被转换为 int 类型。结果 signed char 传播其带符号的位,两个值变得不相等。

为了演示效果尝试运行这个简单的例子

{
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

编辑:直到现在我才看到变量的定义必须看起来像

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

也就是说 b 的定义中的减号不应该出现。

关于c++ - 比较有符号和无符号字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21027305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com