Control flow (or flow of control) refers to the order in which statements are evaluated or executed.
Control flow (or flow of control) refers to the order in which statements are evaluated or executed.
There are many methods to control the flow of execution in a program:
Unconditional jumps can use labels:
foo:
printf ("Hello, world.\n");
goto foo;
... or line numbers:
10 PRINT "something"
20 GOTO 10
Conditional branching can use if-else constructs:
if ($x > 3) {
print "$x is many.";
} else {
print "$x is few.";
}
... or switch statements:
case n of
1 : writeln('one');
2 : writeln('two');
3 : writeln('three');
end;
Loops of various kinds exist, including for loops:
for (var i = 0; i < 9; i++) {
window.alert(i);
}
... foreach loops:
foreach (int x in myArray)
{
Console.WriteLine(x);
}
... and while loops:
while read z
do
echo "Hello, ${z}."
done
Loops can also be terminated early, or made to bypass some of the loop body, with break and continue statements respectively:
for club in ("groucho", "fight", "fight", "kitkat", "drones"):
if club == "fight":
continue
if club == "kitkat":
break
print(club)
Functions temporarily divert execution to named sections of code, before returning:
hello = (name) -> "Hello, #{ name }."
console.log hello "world"
Exceptions are used to divert control flow in exceptional circumstances:
try {
x = 1 / 0;
System.out.println("Hello, world."); // is not reached
} catch (ArithmeticException e) {
System.out.println("Goodbye, world.");
}