Yassine Badache
Yassine Badache

Reputation: 1851

What is the difference between (a != b) and (a != (a = b)?

In a recent question, we found the following piece of code:

// p, t, q and tail are Node<E> objects.
p = (p != t && t != (t = tail)) ? t : q;

Omitting the context of the question, I am interested in the following behavior:

t != (t = tail)

Considering those are the same type of objects, whatever the type. Is there any difference between this and:

t != tail

Or am I missing something crucial in the comparison mechanism ?


EDIT

If anyone wonders, this is found in the ConcurrentLinkedQueue class from java.util, line 352.

Upvotes: 4

Views: 1775

Answers (2)

ammcom
ammcom

Reputation: 1034

The first code:

t != (t = tail)

will assign tail to t then compare t with the new value

the second one will compare t to tail

Upvotes: 3

Eran
Eran

Reputation: 393836

t != (t = tail)

is equivalent to

oldt = t;
t = tail;
... oldt != t...

i.e. the original value of t is compared to tail and in addition t is assigned the value of tail.

It's a short way of writing

if (t != tail) {
    t = tail;
}

Upvotes: 3

Related Questions