Understanding a Julia statement comprising == && increment and continue

106 Views Asked by At

I am trying to translate some Julia routine into C (C#, C++). I fail to understand the particular line

n == n0 && (n+=1; continue)

in the following loop.

ret1, ret2, n = 1, 0, 0
while n < m
    n == n0 && (n+=1; continue)
    ret1 *= z+n
    ret2 += 1/(z+n)
    n += 1
end

How is the increment function before exiting the loop.

1

There are 1 best solutions below

2
StefanKarpinski On BEST ANSWER

In this code, (n+=1; continue) is a compound expression, similar to using a block. The && has short-circuit evaluation semantics, where the right-hand-side is only evaluated if the left-hand-side is true. It would be much clearer and better style, imo, to write this code like this:

ret1, ret2, n = 1, 0, 0
while n < m
    if n == n0
        n += 1
        continue
    end
    ret1 *= z+n
    ret2 += 1/(z+n)
    n += 1
end

Better still, would be to invert the condition and only evaulate the body statements if on the later iterations:

ret1, ret2, n = 1, 0, 0
while n < m
    if n != n0
        ret1 *= z+n
        ret2 += 1/(z+n)
    end
    n += 1
end