Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between (x^y) and !(!(x^y))

I am a new computer science undergrad. For my assignment I need to implement isNotEqual(int x, int y) function in C by just using bitwise operators. This function will return false if x and y are equal, true otherwise. I have tried to just use x ^ y, but it couldn't pass all the test cases. My assumption was if only x and y are equal, it will return as a 0, and if they are not equal, it will return as a non-zero integer. In our first lessons, we learned that C returns non-zero values as true. To solve this problem I tried to use !(!(x ^ y)) and it worked. I can see the difference between my 2 solutions. For the second one, all the bits are converted to '1' but I don't understand why the simpler first solution doesn't work. Can someone explain why my first solution couldn't pass all the tests?

I tried:

int isNotEqual(int x, int y){
    return x^y;
}    

But the correct solution was:

int isNotEqual(int x, int y){
    return !(!(x^y));
}
like image 405
Alper Avatar asked Dec 30 '25 21:12

Alper


2 Answers

You have not shown the text of the assignment. Likely one of these things is true:

  • The assignment specifies to return one if x and y are not equal and zero otherwise. In this case, you need to use return !! (x^y); or equivalent.
  • The assignment specifies to return non-zero if x and y are not equal and zero otherwise. In this case, return x^y; is sufficient and, if the test program complains, it is improperly written.
  • The assignment fails to specify what to return. In this case, the specification is deficient, and you should ask the instructor to complete it.
like image 109
Eric Postpischil Avatar answered Jan 02 '26 13:01

Eric Postpischil


The difference between x^y and !(!(x^y)) is that when x and y are unequal, the former might take a wide range of nonzero values, but the latter will evaluate to exactly 1.

Any non-zero value is truthy in C, so your simpler implementation is plausible. It does not match the behavior of the != operator, however, which always evaluates to either 0 or 1, not any other value. Presumably, then, the latter behavior is what was expected. If the exercise was not clear about that then it was flawed, and you might have a case for a re-grade.

like image 20
John Bollinger Avatar answered Jan 02 '26 14:01

John Bollinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!