mc20
mc20

Reputation: 1175

using or "|" operator for statements in java

Suppose I have an array a[] , if I want to change the value of a[i] and change it to zero , I can do it by using temp variable like.

int temp = a[i];
a[i] = 0;

But I came across a code similar to this

int temp = a[i] | (a[i] = 0);

I had hard time understanding this. Please explain does it work? Is it a good practice to use similar type of code ?

Upvotes: 3

Views: 79

Answers (1)

rgettman
rgettman

Reputation: 178313

The purpose of the straightforward code is to grab a value from an array and set its location in the array to 0.

Let's see how the tricky code does it.

The | operator is the bitwise-or operator. First, a[i] is evaluated, and whatever value is there is the left operand. Next, the parentheses force a[i] = 0 to be evaluated. This sets the array element to 0 and the right operand of | is now 0. Performing a bitwise-or with the value 0 doesn't change the other value. The value of the entire expression on the right of temp = is the original value of a[i]. This has the effect of doing everything the straightforward code does, in one statement.

This code is tricky and it's not good practice, because it's confusing. I would never use such a technique.

Upvotes: 7

Related Questions