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