gpt4 book ai didi

c++ - 有符号/无符号比较

转载 作者:IT老高 更新时间:2023-10-28 12:05:21 33 4
gpt4 key购买 nike

我试图理解为什么下面的代码没有在指定位置发出警告。

//from limits.h
#define UINT_MAX 0xffffffff /* maximum unsigned int value */
#define INT_MAX 2147483647 /* maximum (signed) int value */
/* = 0x7fffffff */

int a = INT_MAX;
//_int64 a = INT_MAX; // makes all warnings go away
unsigned int b = UINT_MAX;
bool c = false;

if(a < b) // warning C4018: '<' : signed/unsigned mismatch
c = true;
if(a > b) // warning C4018: '<' : signed/unsigned mismatch
c = true;
if(a <= b) // warning C4018: '<' : signed/unsigned mismatch
c = true;
if(a >= b) // warning C4018: '<' : signed/unsigned mismatch
c = true;
if(a == b) // no warning <--- warning expected here
c = true;
if(((unsigned int)a) == b) // no warning (as expected)
c = true;
if(a == ((int)b)) // no warning (as expected)
c = true;

我还以为是后台推广的问题,后面两个好像不是这么说的。

在我看来,第一个 == 比较与其他比较一样多是有符号/无符号不匹配?

最佳答案

在比较有符号和无符号时,编译器会将有符号值转换为无符号值。对于平等,这无关紧要,-1 == (unsigned) -1 .对于其他比较,它很重要,例如以下是正确的:-1 > 2U .

编辑:引用:

5/9:(表达式)

Many binary operators that expectoperands of arithmetic or enumerationtype cause conversions and yieldresult types in a similar way. Thepurpose is to yield a common type,which is also the type of the result.This pattern is called the usualarithmetic conversions, which aredefined as follows:

  • If eitheroperand is of type long double, theother shall be converted to longdouble.
  • Otherwise, if either operandis double, the other shall beconverted to double.
  • Otherwise, ifeither operand is float, the othershall be converted to float.
  • Otherwise, the integral promotions(4.5) shall be performed on bothoperands.54)
  • Then, if either operandis unsigned long the other shall beconverted to unsigned long.
  • Otherwise, if one operand is a longint and the other unsigned int, thenif a long int can represent all thevalues of an unsigned int, theunsigned int shall be converted to along int; otherwise both operandsshall be converted to unsigned longint.
  • Otherwise, if either operand islong, the other shall be converted tolong.
  • Otherwise, if either operandis unsigned, the other shall beconverted to unsigned.

4.7/2:(积分转换)

If the destination type is unsigned,the resulting value is the leastunsigned integer congruent to thesource integer (modulo 2n where n isthe number of bits used to representthe unsigned type). [Note: In a two’scomplement representation, thisconversion is conceptual and there isno change in the bit pattern (if thereis no truncation). ]

EDIT2:MSVC 警告级别

MSVC 的不同警告级别所警告的内容当然是开发人员做出的选择。在我看来,他们关于有符号/无符号相等与更大/更少比较的选择是有道理的,这当然是完全主观的:

-1 == -1表示与 -1 == (unsigned) -1 相同- 我发现这是一个直观的结果。

-1 < 2 -1 < (unsigned) 2 的意思相同- 这乍一看不太直观,IMO 值得“更早”警告。

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

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