Next: Continue Statement, Previous: Switch Statement, Up: Statements [Contents][Index]
break
StatementThe break
statement jumps out of the innermost for
,
while
, or do
loop that encloses it. The following example
finds the smallest divisor of any integer, and also identifies prime
numbers:
# find smallest divisor of num { num = $1 for (divisor = 2; divisor * divisor <= num; divisor++) { if (num % divisor == 0) break } if (num % divisor == 0) printf "Smallest divisor of %d is %d\n", num, divisor else printf "%d is prime\n", num }
When the remainder is zero in the first if
statement, awk
immediately breaks out of the containing for
loop. This means
that awk
proceeds immediately to the statement following the loop
and continues processing. (This is very different from the exit
statement, which stops the entire awk
program.
See Exit Statement.)
The following program illustrates how the condition of a for
or while
statement could be replaced with a break
inside
an if
:
# find smallest divisor of num { num = $1 for (divisor = 2; ; divisor++) { if (num % divisor == 0) { printf "Smallest divisor of %d is %d\n", num, divisor break } if (divisor * divisor > num) { printf "%d is prime\n", num break } } }
The break
statement is also used to break out of the
switch
statement.
This is discussed in Switch Statement.
The break
statement has no meaning when
used outside the body of a loop or switch
.
However, although it was never documented,
historical implementations of awk
treated the break
statement outside of a loop as if it were a next
statement
(see Next Statement).
(d.c.)
Recent versions of BWK awk
no longer allow this usage,
nor does gawk
.
Next: Continue Statement, Previous: Switch Statement, Up: Statements [Contents][Index]