teaLeef
teaLeef

Reputation: 1989

Results of comparing integers in C

If x and y are both int, will x-y < 0 always return the same result as x < y?

Upvotes: 2

Views: 89

Answers (2)

hillel_guy
hillel_guy

Reputation: 696

As @sgar91 said, No.

For example:

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

x < y //will be true

Upvotes: 0

Paul Hankin
Paul Hankin

Reputation: 58409

No. If x-y causes overflow or underflow, behavior is undefined (because int is a signed type).

For example INT_MIN - 1 < 0 is undefined behavior, whereas INT_MIN < 1 is defined (and true).

When there's no overflow, then the two expressions, x-y < 0 and x < y are the same.

Because compiled code may do whatever it likes when there's undefined behavior, the C compiler is allowed to rewrite x-y < 0 as x < y if it wishes. This isn't true if x and y are unsigned types, where overflow is well-defined, and x-y < 0 and x < y are not equivalent.

Upvotes: 9

Related Questions