-1

The expression is as follows

(ux-uy) == -(unsigned) (y-x)

where x and y are random integers and ux and uy are declared and defined as follows

unsigned ux = (unsigned) x;
unsigned uy = (unsigned) y;

I tested the expression in c with various numbers and it was correct but I cant prove why it is correct. please explain.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
user1335175
  • 181
  • 7
  • 20
  • Whether `signed` or not is `ux - uy == -(uy - ux)` or not? You think of it as a mathematical problem, and you shall see what is going on. – Iharob Al Asimi Oct 05 '15 at 04:05
  • do a case by case analysis, i.e., when x greater than y by n, y greater than x by n, equal. – perreal Oct 05 '15 at 04:06
  • I am confused about the - sign in front of RHS. what exactly does it do ? – user1335175 Oct 05 '15 at 04:16
  • @user1335175: The `-` sign in front of the cast means that the result is negated, and then converted back to an `(unsigned int)` again (because the LHS of the equality is an `unsigned int`) before the comparison is done. – Jonathan Leffler Oct 05 '15 at 04:28

1 Answers1

2

y-x --> undefined behavior should the int subtraction overflow.

So the equality (ux-uy) == -(unsigned) (y-x) fails, in general.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256