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.
The conditional statement is called if. The syntax is:
if (cond) stmt1; if (cond) 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.
Syntax:
while (cond) stmt
while (cond) stmt
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) { n = 1; while (n < 4) { fawk_print(n); n++; } } |
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.
Syntax:
do stmt while (cond)
This will execute stmt repeatedly, 1 or more times, as long as cond is true . For example the following script will print 1, 2 and 3:
example program ch3_ex2 |
---|
function main(ARGV) { n = 1; do { fawk_print(n); n++; } while (n < 4); } |
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 false in the first iteration.
Syntax:
for (init; cond; step) stmt
The for loop is a shorthand to the following, more verbose code:
init while (cond) { stmt step }
which makes the for loop a pre-test loop. The following example prints numbers 1, 2 and 3 (and is equivalent to the example in 3.3):
function main(ARGV) { for(n = 1; n < 4; n++) fawk_print(n); }
Note: unlike in C, there is no comma operator in fawk, so something like n = 1, b = 2 as init will not work.