Why doesn't this program short circuit?

Viewed 77

Running gnu awk I get a div/0 error. Mawk does not have the same error.

>>> awk 'BEGIN { print (0 && (4/0)) }'
awk: cmd. line:1: error: division by zero attempted
>>> mawk ''BEGIN { print (0 && (4/0)) }'
0

If I add parenthesis around the 4 it behaves the same

>>> awk "BEGIN { print (0 && ((4)/0)) }"
0
>>> mawk "BEGIN { print (0 && ((4)/0)) }"
0

Which seems like it should not matter.

Looking through the posix standard I can't actually find the words short circuiting, so are both correct? Just mawk?

GNU awk does say this

The ‘&&’ and ‘||’ operators are called short-circuit operators because of the way they work. Evaluation of the full expression is “short-circuited” if the result can be determined partway through its evaluation.

1 Answers

By default, gawk optimises code with constant-folding.
This happens before the program is run.

It can be turned off with -s:

$ gawk 'BEGIN { 0 && 4/0; print "ok" }'
gawk: cmd. line:1: error: division by zero attempted
$ gawk -s 'BEGIN { 0 && 4/0; print "ok" }'
ok
$
Related