Search code examples
comparison-operatorschainedjulia

Priority in chained comparisons in Julia, does "var1 && var2 != 1" mean "(var1 and var2) != 1"?


I have a questions regarding the chained comparisons in Julia. I read this section in the manual but it is still unclear.

In Julia, does this:

if var1 && var2 != 1

mean this (in Python):

if (var1 and var2) != 1:

Thank you!


Solution

  • From what I could read on that page and a linked page (http://docs.julialang.org/en/latest/manual/control-flow/#man-short-circuit-evaluation), no. The order of operations is different. It ends up like this:

    if (var1) && (var2 != 1)
    

    First, the xscalar variable gets checked for a value that would satisfy an if statement, as if you did

    if var1
    

    Then, if, and only if that is accepted, does the next part get evaluated:

    if var2 != 1
    

    In other words, these two statements are roughly equivalent:

    if var1
        if var2 != 1
    
    and
    
    if var1 && var2 != 1
    

    (forgive the lack of julia syntax knowledge)

    A python equivalent of this would be:

    if var1 and var2 != 1:
    

    or, with parentheses to show with more clarity,

    if (var1) and (var2 != 1) :