-2

When I write like below

int [] test = {4};
int a = test[0]^=1;
int b = test[0]^1;

I can get this output.

OUTPUT

test[0]^=1 : 5 a : 101
test[0]^1 : 4 b : 100

I think that test[0] = 100 -> test[0]^1 = 101 but it is not.

      100 
  XOR   1
----------
      101

Would you expain what is different?

Mj choi
  • 69
  • 1
  • 9
  • `test[0]^=1` is a statement, `test[0]^1` is expression. – Aniket Sahrawat Mar 07 '21 at 12:55
  • After first XOR operation the value in array test[0] is also updated that why after second XOR you get the same result. **test[0]^=1 equivalent to test[0]= test[0] ^ 1** – Jimmy Mar 07 '21 at 13:02
  • I'd like to say, that it's unclear whether your question is "how does `test[0]^=1` work?" or "how do bitwise operators work?". I guess it's both, in your case, but it's always better to clarify what you're exactly asking about, as these two concepts (compound assignment and bitwise) are two, absolutely different topics. – Giorgi Tsiklauri Mar 07 '21 at 13:04

1 Answers1

0

It's because test[0] value already changed to 101 because of test[0]^=1. test[0]^=1 which is actually test[0] = test[0] ^ 1. So while doing b = test[0] ^ 1 you are actually doing 101 ^ 1 which is 100. So the program output is correct.

int [] test = {4};   // test[0] = 4 = 100
int a = test[0]^=1;  // test[0] = 100 ^ 1 = 101 = 5, a = 5 = 101
int b = test[0]^1;   // test[0] = 5, b = 101^1 = 100 = 4
MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37