danger mouse
danger mouse

Reputation: 1497

Java assignment operator

The following blockquote is taken from http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html

Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example:

if (c++ = d++) {        // AVOID! (Java disallows)
    ...
}

should be written as

if ((c++ = d++) != 0) {
    ...
}

I am confused by the line

if ((c++ = d++) != 0) {

Any clarification on this would be appreciated.

Upvotes: 2

Views: 437

Answers (4)

selbie
selbie

Reputation: 104464

(c++ = d++) is an integer expression, not a boolean expression. It evaluates to whatever integer c got assigned to in the c++ = d++ assignment. Hence if (c++ = d++) { is a non starter in java.

So the comparison with 0 is what it takes to convert the integer expression to boolean.

And I think it goes without saying. Code written as follows:

if ((c++ = d++) != 0) {

is just bad coding. First, the the inner assignment within a comparison. Then the postfix operators within it. Both contribute to a block of code that is difficult to read, easy opportunities for bugs, difficult to maintain etc... Better written as follows:

c = d;
c++;
d++;
if (c == d) {

But you already knew that. :)

Upvotes: 0

ctt
ctt

Reputation: 1435

They're just trying to say that the compiler requires the condition of an if statement to evaluate to a boolean value. If you know what you're doing, and decide to put actual code with side effects as the condition, you're required to make the expression evaluate to a value of type boolean.

Whereas the anti-pattern code in the example would work out in a programming language like C where boolean values are actually integers (where zero is false, and non-zero is true), the proper way to do this in Java is to actually compare the result to 0.

Upvotes: 0

Aniket Thakur
Aniket Thakur

Reputation: 68905

At the very beginning of the page I can see -

This page is not being actively maintained. Links within the documentation may not work and the information itself may no longer be valid. The last revision to this document was made on April 20, 1999

    if ((c++ = d++) != 0) {
        //logic
    }

Syntax is not even valid (Using Java6). It gives me

The left-hand side of an assignment must be a variable

You need to assign c++ to some variable.

Upvotes: 1

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10288

In contrast with other languages like C, Java's scalar primitives (integers, etc.) cannot be used as booleans. In other words, 0 is in no sense either true or false. Only whether something is equal to 0 can be true or false.

Upvotes: 1

Related Questions