|
|
The if statement's generic syntax is as follows:
if (expression) statement1[ else statement2]
The expression acting as the conditional has no restrictions; it can include the relational operators <, <=, >, >=, ==, and !=; the regular expression matching operators ~ and !~ ; the logical operators ||, &&, and !; juxtaposition for concatenation; and parentheses for grouping.
In the if statement, the expression is first evaluated. If it is nonzero and non-null, statement1 is executed; otherwise statement2 is executed. The else part is optional.
A single statement can always be replaced by a statement list enclosed in braces. The statements in the statement list are terminated by newlines or semicolons.
The following is a rewrite of the maximum population program from ``Performing arithmetic'', using an if statement:
BEGIN { minpop=1000; maxpop=0; mincountry=""; maxcountry="" } { if (maxpop < $3) { maxpop = $3 maxcountry = $1 } else { if (minpop > $3) { minpop=$3 mincountry=$1 } } } END { print maxcountry, maxpop print mincountry, minpop }The following output results:
China 866 Australia 14