Short circuit estimation causing wrong destination location error
The docs for Julia indicate that a valid shorthand for writing a statement if
is the syntax
<cond> && <statement>
I've used this for error reporting eg. length(x) < N && error("x is too short")
and it works as expected. However the following doesn't work:
x = 3 x < 4 && x = 5
I am getting a form error syntax: invalid assignment location
. What's going on here?
What I'm trying to do is check if x
less 4
, and if there 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?
source to share
Your error is caused by the operator &&
having a higher precedence than the assignment operator =
, so your line of code is executed as if you were writing (x < 4 && x) = 5
.
For the solution, you need to add parentheses.
x < 4 && (x = 5)
source to share