(gawk.info) Break Statement
Info Catalog
(gawk.info) For Statement
(gawk.info) Statements
(gawk.info) Continue Statement
The `break' Statement
=====================
The `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:
awk '# find smallest divisor of num
{ num = $1
for (div = 2; div*div <= num; div++)
if (num % div == 0)
break
if (num % div == 0)
printf "Smallest divisor of %d is %d\n", num, div
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. The `exit'
Statement Exit Statement.)
Here is another program equivalent to the previous one. It
illustrates how the CONDITION of a `for' or `while' could just as well
be replaced with a `break' inside an `if':
awk '# find smallest divisor of num
{ num = $1
for (div = 2; ; div++) {
if (num % div == 0) {
printf "Smallest divisor of %d is %d\n", num, div
break
}
if (div*div > num) {
printf "%d is prime\n", num
break
}
}
}'
As described above, the `break' statement has no meaning when used
outside the body of a loop. However, although it was never documented,
historical implementations of `awk' have treated the `break' statement
outside of a loop as if it were a `next' statement ( The `next'
Statement Next Statement.). Recent versions of Unix `awk' no longer
allow this usage. `gawk' will support this use of `break' only if
`--traditional' has been specified on the command line ( Command
Line Options Options.). Otherwise, it will be treated as an error,
since the POSIX standard specifies that `break' should only be used
inside the body of a loop (d.c.).
Info Catalog
(gawk.info) For Statement
(gawk.info) Statements
(gawk.info) Continue Statement
automatically generated byinfo2html