Comment

Comment by alangpierce

Interesting, my intuition is the opposite: that left-to-right evaluation is clearly the better approach. I just tested a few languages and it turns out that there's no clear agreed-upon answer, but LHS first seems to be more common at least for recent languages:

LHS first: JavaScript, Java, Go, C#, Swift, PHP, Ruby

RHS first: C++, Python, Rust

I ran this sort of code for all of them:

    def lhs(): print "LHS"; return 0
    def rhs(): print "RHS"; return 0
    a = [0]
    a[lhs()] = rhs()
"=" is syntactically just a binary operator, so I expect it to behave like other binary operators (and AFAIK all other binary operators evaluate left-to-right in almost all languages). It's special because the LHS evaluates to an assignable reference rather than to a value, but nothing stops you from evaluating the left side in full before starting to evaluate the right side. As with every binary operator, it's possible to write code such that the evaluation of one side affects the result of evaluating the other side, but of course that sort of code is really fragile anyway.
parent alangpierce 8 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton