Short circuit evaluations documentation when using assignment statement

I love the idea of short circuit evaluations. Took me a while to figure out why a piece of code wasn’t working–short circuit evaluation documentation in the Manual section lacks clarity when using an assignment on the right.

Failing code:

n = 1
n < 1 && n = 5

ERROR: syntax: invalid assignment location “(n < 1) && n” around REPL[11]:1
[1] top-level scope
@ REPL[11]:1

I would like to see an addition to the short circuit documentation clarifying the use of an assignment on the right side. Something like:

When using an assignment on the right side of a short circuit evaluation, the assignment statement must be enclosed in parenthesis.

n = 0
n < 1 && x = 5 # Incorrect

n < 1 && (x = 5) # Correct

(n < 1) && (x = 5) # Correct

However, at first glance, the reader might see this as a logical “and” operation and interpret the flow of the statement incorrectly.

I personally would suggest dropping the “||” short circuit and using something such as the keyword “then” in place of the “&&”. In my mind, this leads to a clearer understanding of the code’s function. It might look like:

n < 1 then x = 5

The false logic can be accommodated by

!(n < 1) then x = 5

Just thinking…

It is more about operator precedence,, but a short note about this in the section about short-circuit evaluation,, with a simple example would be no harm.

You can easily create a PR to change

1 Like

I learned this the hard way. One way to see how hard it will be for the compiler to figure it out without the parens is a MWE of the thing I broke

x > 2 || x < -1 || x=4

I found the error message unusually informative

ERROR: syntax: invalid assignment location "(x > 2) || (x < -1) || x" around REPL[8]:1

and learned my lesson. I’m pretty happy with the way this works, now that I understand it better.

Agree that the docs could me more clear on this.

1 Like

To me, this looks like a place for a better error message. I’ll see if I can fix it.

1 Like

That’s unlikely to happen, see

The error message could be improved though.

1 Like