[英]Results of comparing integers in C
如果x
和y
都是int
, xy < 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 < 0
和x < 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. 如果
x
和y
是无符号类型,其中溢出是明确定义的,并且xy < 0
且x < 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.