bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

evaluating "&&" order with div by zero in subsequent part.


From: Ed Morton
Subject: evaluating "&&" order with div by zero in subsequent part.
Date: Sun, 14 Aug 2022 07:39:07 -0500
User-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Thunderbird/102.1.0

There's some inconsistency in the following division by zero treatment  (gawk 5.1.1 on cygwin):

Let's say we have a script that's trying to divide 4 by some number if that input value is non-zero:

   $ echo 2 | awk '{ print ($0 && (4/$0)) }'
   1

These all make sense, dividing by that input value:

   $ echo 0 | awk '{ print ($0 && (4/$0)) }'
   0
   $ echo 0 | awk '{ print (0 && (4/$0)) }'
   0
   $ echo 0 | awk '{ print ($0 && (4/($0+0))) }'
   0

but then if we swap denominator $0 which has value 0 with literal 0:

   $ echo 0 | awk '{ print (0 && (4/0)) }'
   awk: cmd. line:1: error: division by zero attempted

and if we then put parens around the numerator 4 and leave the denominator 0:

   $ echo 0 | awk '{ print (0 && ((4)/0)) }'
   0

Since the manual at https://www.gnu.org/software/gawk/manual/html_node/Boolean-Ops.html says (emphasis mine):

|boolean1 && boolean2|

    True if both boolean1 and boolean2 are true. For example, the
    following statement prints the current input record if it contains
    both ‘edu’ and ‘li’:

    if ($0 ~ /edu/ && $0 ~ /li/) print

    *The subexpression **boolean2**is evaluated only if **boolean1**is
    true. *


I'd have expected that in all cases except the first script above, since the first part of the compound condition evaluates to `0 &&` that the second part that contains the divide by zero wouldn't be evaluated and we'd always print 0. Having said that, I can see that if there's a piece of code with a constant 0 as the denominator that it'd be good to get a divide by zero error in case that's ever hit as that's obviously a bug, but then I'd have expected puting parens around `4` not to change the behavior.

Regards,

    Ed.








reply via email to

[Prev in Thread] Current Thread [Next in Thread]