Chapter 3: Flow control

3.1. void expression

A function body is a sequence of statements. So far all our statements were "void expressions" - an expression whose result is discarded.

This chapter shows all the other statements available. These statements change the flow of program execution: instead of sequentially executing statements they can selectively skip some statements or execute some statemets repeatedly.

3.2. conditional: if

The conditional statement is called if. The syntax is:

if cond then stmt1;
if cond then stmt1 else stmt2;

where cond is an expression that is evaluated. If the result is true, stmt1 is executed (else it is skipped). stmt1 is a single statement (or a block, see chapter 1). If an else is present,when cond is false, stmt2 is executed. It is very important that semicolon must be omitted after stmt1 when else follows. This helps the compiler decide which if an else is for in nested cases. But it is best practice to use begin-end blocks in such situatons.

3.3. pre-test loop

Syntax:

This will execute stmt repeatedly, 0 or more times, as long as cond is true. For example the following script will print 1, 2 and 3:
example program ch3_ex1
function main(ARGV);
begin
	n := 1;
	while n < 4 do
	begin
		fawk_print(n);
		n := n+1;
	end;
end;

It is a pre-test loop because cond is evaluated before executing stmt - this can result in zero executions of stmt if the condition is false before the first iteration.

3.4. post-test loop

Syntax:

repeat
	stmt
	stmt
until cond

This will execute stmt repeatedly, 1 or more times, as long as cond is false . For example the following script will print 1, 2 and 3:
example program ch3_ex2
function main(ARGV);
begin
	n := 1;
	repeat
		fawk_print(n);
		n := n + 1;
	until n > 3;
end;

It is a post-test loop because cond is evaluated after executing stmt - this means stmt is always executed at least once, even if the condition is true in the first iteration.

3.5. for loop

Syntax:

for var := expr1 to expr2 do
	stmt

or

for var := expr1 downto expr2 do
	stmt

The for loop runs var from value expr1 to expr2 in +1 increments or -1 decrements depending on whether to or downto was used.

The following example prints numbers 1, 2 and 3 (and is equivalent to the example in 3.3):

function main(ARGV);
begin
	for n := 1 to 3 do
		fawk_print(n);
end;

Note: the value of n after the loop is the last value it had in the loop: expr2, where the loop has terminated.