I get six different results when dividing by zero in mawk:
$ echo | awk '{print -1/0 }' ; echo $?
-inf
0
$ echo | awk '{print 0/0 }' ; echo $?
-nan
0
$ echo | awk '{print 1/0 }' ; echo $?
inf
0
$ echo | awk '{printf ("%i\n", -1/0) }' ; echo $?
-2147483647
0
$ echo | awk '{printf ("%i\n", 0/0) }' ; echo $?
-2147483647
0
$ echo | awk '{printf ("%i\n", 1/0) }' ; echo $?
2147483647
0
I get a “success” exit code for each case.
- Why does this happen?
- What can I do about it? Do I always have to check for zero divisors before doing a division or is there a way I can rely on awk’s error handling and exit codes?
I’m guessing you are using
mawk, none ofawk,nawkorgawkhave this behaviour, division by zero is not supported on those.Your answers are
+inffor positive infinity,nanfor “not a number” and-inffor negative infinity, all as expected. These are only output when printing a float, i.e. with%.6gwhich is the defaultOFMT(default format used for printing numbers).When you print explicitly with “%i” you get +HUGE or -HUGE instead, this is converted to an int (signed 32-bit in your case) and printed as + or – (2^31-1).
The usual practice is to always check for divide by zero, ideally minimising the number of times you need to check by reorganising your expressions — divide by zero causes other implementations of awk to simply terminate.
When
mawkis building it detects the capabilities of your C math library:You can get “standard” behaviour if you build with
NOINFO_SIGFPEdefined:(though this isn’t documented, it may not be something you should rely on).