Detect division by zero: Difference between revisions

Content deleted Content added
PureFox (talk | contribs)
Line 844:
end program rosetta_integer_divbyzero
</lang>
 
=={{header|FreeBASIC}}==
In FreeBASIC integer division by zero is a fatal error and cannot be caught by the language's built-in error handling constructs.
However, it is possible to detect such an error by using floating point division instead and relying on the fact that when Infinity, -Infinity and NaN are converted back to a 4 or 8 byte signed integer, the result is the lower bound of the range of the relevant integer type.
 
For Win64, an Integer is a signed 8 byte type and the returned value is therefore -9223372036854775808 which would be unlikely to arise in any other integer division scenario.
 
The following code relies on this 'hack':-
 
<lang freebasic>' FB 1.05.0 Win64
 
Const divByZeroResult As Integer = -9223372036854775808
 
Sub CheckForDivByZero(result As Integer)
If result = divByZeroResult Then
Print "Division by Zero"
Else
Print "Division by Non-Zero"
End If
End Sub
 
Dim As Integer x, y
 
x = 0 : y = 0
CheckForDivByZero(x/y) ' automatic conversion to type of parameter which is Integer
x = 1
CheckForDivByZero(x/y)
x = -1
CheckForDivByZero(x/y)
y = 1
CheckForDivByZero(x/y)
Print
Print "Press any key to exit"
Sleep</lang>
 
{{out}}
<pre>
Division by Zero
Division by Zero
Division by Zero
Division by Non-Zero
</pre>
 
=={{header|FutureBasic}}==