Archived

This topic is now archived and is closed to further replies.

RabidCow

Divide by zero in my interpreter

Recommended Posts

I''m in the process of writing an interpreter for a language I''m making up as a I go. I''m unsure of how I should handle a divide by zero, so I figured I''d ask the people here which they''d like better. Should I have the interpreter generate an error (and halt the program), or should it return a nil value (which would generate an error and halt the program if you tried to use it as a number)?

Share this post


Link to post
Share on other sites
I''d make it a "hard" runtime error and stop the program at that point. A division by zero has no valid result and should be avoided by the program doing the division. Trying to produce a return value can only hurt correctness.

Share this post


Link to post
Share on other sites
Hmm... I was gonna suggest having some flags that you could set, to see if a division by zero happened, without crashing. So you would do the division, and then if you were interested, you could check the flag. However, I realized that if people want to check for division by zero, then they should be using an if statement beforehand anyway, to check for the denomintor equaling zero. Same amount of effor for the programmer. Less effort and simpler design for the interpreter. So I''d agree with Shadowdancer and make it a hard error as well.

Share this post


Link to post
Share on other sites
If it''s a float, don''t even check and just let it go with the infinity you''d normally get. For integers, kill the program.

Share this post


Link to post
Share on other sites
The best way would be to hook some kind of interrupt and have it nail your handler when it explodes. I have no idea how you''d do it in portable C... but testing every time you do an op slows things down considerably.

op_div( a,b )
{
if( b == 0 )
exception(DIV_BY_ZERO)

r = a / b;
}

would be better like something like

signal_handler(DIV_BY_ZERO, oops_div );

oops_div() { print "divide by zero"; exit(0); }

op_div(a,b)
{
r = a/b;
}

then when a division by zero occurs it executes your signal handler instead.



Share this post


Link to post
Share on other sites