Colin T Bowers
Colin T Bowers

Reputation: 18580

Short circuit evaluation causing an invalid assignment location error

The docs for Julia indicate that a valid short-cut to writing out an if statement is the syntax

<cond> && <statement>

I've used this a lot for error messages, e.g. length(x) < N && error("x is too short"), and it works as expected. However, the following does not work:

x = 3
x < 4 && x = 5

I get an error of the form syntax: invalid assignment location. What is going on here?

What I'm trying to do is check if x is less than 4, and if it is, then set x to 5. Should I do the following?

if x < 4
     x = 5
end

Is there a valid short-circuit method for this situation?

Upvotes: 3

Views: 701

Answers (1)

halex
halex

Reputation: 16403

Your error is caused because the && operator has higher precedence than the assignment operator = so your line of code is executed as if you would write (x < 4 && x) = 5.

For a solution you have to add parantheses.

x < 4 && (x = 5)

See my code running in the browser

Upvotes: 9

Related Questions