Integrity of parentheses?

Does the Julia language guarantee evaluation order where parentheses are used to isolate subexpressions? For example, if one writes

d = a + (b - c)

can we be sure that the subtraction is performed first? This is important in implementing algorithms where one attempts to control roundoff.

I didn’t find a statement to this effect in the manual, but it appears to be the case in my (very limited) investigations. Note that some languages (e.g. Fortran) do have such a guarantee, but others (e.g. C, at least when I learned it) do not. Even if it’s true in practice now, without a guarantee (and tests!) some future “optimization” may break it.

julia> Meta.@lower d = a + (b - c)
:($(Expr(:thunk, CodeInfo(
 1 ─ %1 = b - c      
 │   %2 = a + %1     
 │        d = %2      
 └──      return %2     
))))

might be a useful tool to see what is happening “under the hood”.

1 Like

Yes, this is guaranteed and is the main purpose of parenthesizing arithmetic expressions.

Are you sure about your statement about C? I only know of undefined order in which modifying operators take effect, e.g. (++i)*(++i) is not defined, but I would first consult a reference on the question wether a + (b + c) can legally evaluated as (a + b) + c in C.

It’s not valid to do (a + b) + c. It’s the order that’s undefined, not the operation preformed

1 Like

Harbison and Steele explicitly say that a C compiler may reorder evaluation of such expressions, and the references I could find online do not disagree.

C compiler has flags to allow that, but doing such transformation changes the operation preformed so it’s not allowed by the standard.

Thanks Stefan, I hoped that would be the case.

And note that they are removing/have removed this undefinedness in c and c++ standard. On my phone so I can’t find the proposal about it.