4

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.

  • 3
    Not a Julia expert, but looks like it wants to skip the iteration where `n==n0`. `&&` is short-circuit evaluating just as in C, so the right-hand side of it will be only evaluated if the left-hand is true. In that case it will increment `n` and skip to the next iteration. – Eugene Sh. Apr 17 '23 at 17:20

1 Answers1

4

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
AboAmmar
  • 5,439
  • 2
  • 13
  • 24
StefanKarpinski
  • 32,404
  • 10
  • 86
  • 111
  • 1
    Continuing with the refactoring theme, this should actually be a `for` loop: `ret1, ret2 = 1.0, 0.0; for n in 0:m-1 ; n == n0 && continue ; ret1 *= z+n; ret2 += 1/(z+n); end` – Dan Getz Apr 17 '23 at 18:00
  • 1
    ...and another refactor: `ret1 = prod(z+n for n in 0:m-1 if n != n0); ret2 = sum(1/(z+n) for n in 0:m-1 if n != n0)` – Dan Getz Apr 17 '23 at 18:41