Comparisons in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int n1 = -1;
int n2 = 2;

unsigned int u1 = (unsigned int) n1;  
unsigned int u2 = (unsigned int) n2;

  

  // I said the result would always be 1 (True) because we are changing the sign 
  // as well as the comparison operator on the RHS.
  int result = (n1 < n2) == (-n1 > -n2);

  
*******************************************************************************
  // For this I said result would always be 0(False) because we are treating both   the LHS and RHS differently in terms of bit inversion.  The variables are the same but on the RHS the value is first summed and then bits inverted. Am I right?
  result = ~n1 + ~n2 == ~(n1 + n2);

******************************************************************************
  // This one was a bit strange to me, but since the right bitwise shift implies and division and the left shift implies multiplication, the result in all of my cases was true that the value on the LHS was 1 less than the value on the RHS.

  result = ((n1 >> 1) << 1) <= n1;
*******************************************************************************

  // a bit stumped about this one....
  result = ((int) (u1 - u2)) == -(n2 - n1);



I hope the format is correct this time.

Last edited on
 
result = ((n1 >> 1) << 1) <= n1;

You have missed something on this one :)
You are taking N1 and shifting all the bits to the right by 1. The result of this has all the bits shifted to the left. IF.. IF the right-most bit was originally 1, when it's shifted to the right it is lost, so shifting it back to the left again would put a 0 in it's place, effectively changing the value of N1. So N1 would always be less than of equal to the RHS.

result = ((int) (u1 - u2)) == -(n2 - n1);
is (u1-u2) the same as negative (n2-n1).

e.g.
U1 = 4
U2 = 9
= (4 - 9) == -(9 - 4)
= (-5) == -(5)
= -5 == -5
= True
@Zaita,

Thanks a lot. You rock!!!
No worries :)
Topic archived. No new replies allowed.