Short circuit evaluation with an assignment statement

There is an example in the (increasingly more excellent) manual under short circuit evaluation that shows an assignment statement as the follow-on statement:

julia> true && (x = (1, 2, 3))
(1, 2, 3)

julia> false && (x = (1, 2, 3))

The example is clear enough, but the manual doesn’t say why an assignment statement is different than a statement with side effects, say a println(“something”). Just curious about why…

1 Like

Not sure what the exact question is but one “difference” is that you need the paranthesis on the right hand side when making an assignment.

The question is WHY are the parens needed for the statement on the right side when it is an assignment statement as opposed to, say, a function call.

Because of presedence. Otherwise it is

(false && x) = (1,2,3)

1 Like

Interesting that = doesn’t have higher precedence than a boolean operator. But, it is what it is and has been since the beginning.


It makes sense for assignment to have lower presedence, consider a = b==c, you don’t want that to be read as (a=b) == c


Or even more pertinent to this question, you want

x = y && z

to parse as x = (y && z) not as (x = y) && z. Therefore, = must have lower precedence than && and you also have

x && y = z

parsing as (x && y) = z rather than x && (y = z). If && and = had adjacent precedence levels, you could just put them on the same level and make them left-associative, but they are separated by several precedence levels so that’s not feasible. It might just be possible to break the usual precedence parsing model and give = different precedence on the LHS here than on the RHS, but that’s getting into pretty dicey parsing territory.

1 Like

I think parens are fine to be explicit about the order of operation intended: as in nearly every expression. I was lulled into thinking of short circuit evaluation as a way to “run” commands, not as an expression in its own right. As
the logic table in the documentation makes clear, it is a Boolean expression. It’s just a bit of a trick that we can employ it as a device to run commands as a shortcut to a slightly longer if block. I was merely surprised by the obvious. No serious or
valid recommendation to change anything here.

Thanks, all.

1 Like

The presedence and parsing of = has been used constructively by many domain-specific languages. Below is an example from Modia that makes use of the fact that julia happily parses any valid expressio on the lhs of = (If I’m not mistaken, one of the many reasons Julia was chosen as the host language of Modia)

@model FirstOrder begin
     x = Variable(start=1)   # start means x(0)
     T = Parameter(0.5)      # Time constant
     u = 2.0                 # Same as Parameter(2.0)
  @equations begin
     T*der(x) + x = u        # der() means time derivative
1 Like