While doing some development work, I yet again run into the CONTINUE
command, which I never really understood why anybody should use it.
If we take the example from Beckhoff's documentation:
FOR nCounter :=1 TO 5 BY 1 DO
nInt1:=nInt1/2;
IF nInt1=0 THEN
CONTINUE; (* to provide a division by zero *)
END_IF
nVar1:=nVar1/nInt1; (* executed, if nInt1 is not 0 *)
END_FOR;
nRes:=nVar1;
Couldn't we achieve the same result by inverting the IF
statement:
FOR nCounter :=1 TO 5 BY 1 DO
nInt1:=nInt1/2;
IF nInt1 <> 0 THEN (* inverted *)
nVar1:=nVar1/nInt1; (* executed, if nInt1 is not 0 *)
END_IF
END_FOR;
nRes:=nVar1;
I have the impression that in all cases, it's possible to use an IF
rather than CONTINUE
.
I'd like to know if you have a counter-example, or cases where the CONTINUE
command has a real advantage when programming a loop.
There is always going to be a way to express the same logic without using CONTINUE
. In many cases it can be done with just an IF block, but in sometimes it is a bit more complicated, such as if the CONTINUE
is used inside an IF
block that is inside the FOR
loop.
Ultimately, it is a matter of preference. I often use CONTINUE
in cases where it avoids creating an indentation level for the code that follows. Some people may hate CONTINUE because "GOTO
considered harmful" (CONTINUE
is not the same as GOTO
, it does not allow jumping to arbitrary code locations).
There probably are cases where CONTINUE
saves some CPU cycles, but it is likely to be so negligible that there are no cases where that would be a practical concern or justification.
So, to sum it up, CONTINUE
has an advantage when it yields code that is easier to understand, which is subjective, so it is up to you to decide.