gpt4 book ai didi

c++ - 无符号和有符号类型的相等操作数行为

转载 作者:太空狗 更新时间:2023-10-29 19:59:25 29 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Signed/unsigned comparisons

所以我有下面的代码,它将一个无符号整数设置为一个负数,然后将无符号整数与相同的负数进行比较。我得到的输出是“不等于”。我了解到,将 unsigned int 设置为 -1 时,在这种情况下 unsigned int 的值设置为 255。

#include <stdint.h>
#include <iostream>

int main(int argc, char **argv)
{
uint8_t test = 0;
int8_t set = -1;

test = set;

if (test == set) {
std::cout << "Equal";
} else {
std::cout << "Not Equal";
}
}

但是,是什么导致相等操作数返回 false?这似乎与类似问题Signed/unsigned comparisons的答案形成鲜明对比。哪个州

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

If either operand is of type long double, the other shall be converted to long double.

Otherwise, if either operand is double, the other shall be converted to double.

Otherwise, if either operand is float, the other shall be converted to float.

Otherwise, the integral promotions (4.5) shall be performed on both operands.54)

Then, if either operand is unsigned long the other shall be converted to unsigned long.

Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.

Otherwise, if either operand is long, the other shall be converted to long.

Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

因此根据这个答案,因为两个操作数都是无符号的,所以另一个应该被转换为无符号的,并且相等应该通过。但它显然没有通过,并且正如这个问题中已经回答的那样,它们都被提升为签名整数。

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