简体   繁体   English

在C中比较整数的结果

[英]Results of comparing integers in C

如果xy都是intxy < 0总是会返回与x < y相同的结果吗?

No. If xy causes overflow or underflow, behavior is undefined (because int is a signed type). 否。如果xy导致溢出或下溢,则行为未定义(因为int是带符号的类型)。

For example INT_MIN - 1 < 0 is undefined behavior, whereas INT_MIN < 1 is defined (and true). 例如, INT_MIN - 1 < 0是未定义的行为,而INT_MIN < 1是定义的(和真)。

When there's no overflow, then the two expressions, xy < 0 and x < y are the same. 当没有溢出时,两个表达式xy < 0x < y是相同的。

Because compiled code may do whatever it likes when there's undefined behavior, the C compiler is allowed to rewrite xy < 0 as x < y if it wishes. 因为编译后的代码可能会在出现未定义的行为时执行任何操作,因此如果需要,C编译器可以将xy < 0重写为x < y This isn't true if x and y are unsigned types, where overflow is well-defined, and xy < 0 and x < y are not equivalent. 如果xy是无符号类型,其中溢出是明确定义的,并且xy < 0x < y不等效,则不是这样。

As @sgar91 said, No. 正如@ sgar91所说,没有。

For example: 例如:

X=0x80000000 //which is IntMin Y=1 xy < 0 // will be false as xy = 0x7FFFFFFF = +Maxint
but

x < y //will be true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM