help-gawk
[Top][All Lists]
Advanced

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

Re: Make division by zero legal


From: Andrew J. Schorr
Subject: Re: Make division by zero legal
Date: Mon, 2 Aug 2021 16:22:40 -0400
User-agent: Mutt/1.5.21 (2010-09-15)

On Mon, Aug 02, 2021 at 04:12:08PM +0200, Nethox wrote:
> On Sun, Aug 1, 2021 at 7:24 PM Peng Yu <pengyu.ut@gmail.com> wrote:
> > [...]
> > In the meantime, what is the best walkaround to get awk conformed to
> > the IEEE standard?
> 
> $ gawk -V | head -1
> GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.0.2, GNU MP 6.1.2)
> 
> $ gawk -M 'BEGIN { print 1/0; print "workaround" }'
> +inf
> workaround

I don't see any mention of this issue in the Posix AWK spec. It's most likely
an implementation-specific decision, as evidenced by the different behavior
when -M is used, or in mawk. It's easy enough to change the regular behavior;
for example, we could downgrade it to a warning:

diff --git a/interpret.h b/interpret.h
index 2ed4f01..681aedb 100644
--- a/interpret.h
+++ b/interpret.h
@@ -583,7 +583,7 @@ exp:
 quotient:
                        t1 = TOP_NUMBER();
                        if (x2 == 0)
-                               fatal(_("division by zero attempted"));
+                               warning(_("division by zero attempted"));
                        r = make_number(t1->numbr / x2);
                        DEREF(t1);
                        REPLACE(r);

Although this fixes only runtime division by zero errors. To handle
the example where it's hardcoded in the program, we also need this:

diff --git a/awkgram.y b/awkgram.y
index e4c9708..715e3c5 100644
--- a/awkgram.y
+++ b/awkgram.y
@@ -5467,8 +5467,8 @@ mk_binary(INSTRUCTION *s1, INSTRUCTION *s2, INSTRUCTION 
*op)
                        case Op_quotient:
                                if (n2->numbr == 0.0) {
                                        /* don't fatalize, allow parsing rest 
of the input */
-                                       error_ln(op->source_line, _("division 
by zero attempted"));
-                                       goto regular;
+                                       warning_ln(op->source_line, _("division 
by zero attempted"));
+                                       /* goto regular; */
                                }
 
                                res /= n2->numbr;


With that:

bash-4.2$ ./gawk 'BEGIN {print 1/0 }'                                       
gawk: cmd. line:1: warning: division by zero attempted
+inf

Or:

bash-4.2$ ./gawk '{print 1/$1}'                                       
5
0.2
0
gawk: cmd. line:1: (FILENAME=- FNR=2) warning: division by zero attempted
+inf

There are other places that generate fatal division by zero errors, so the full
patch would be bigger. I can't speak to why gawk currently crashes on division
by zero; it does seem odd that -M behaves differently.

Regards,
Andy



reply via email to

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