Hello, i want to handle overflow/underflow on int operation of add, sub, mul, and div
Expecting the following to raise overflow, but it did not, it wraps the int value does the compiler helps finding this potentially overflow operations?
Thank you friends!
import strutils
{.overflowChecks: on.}
proc something() =
var input: string
if readLine(stdin, input):
echo "input > ", input
var x = 0'u8
try:
x -= input.parseInt().uint8
x -= 1 # OverflowDefect
x = x - 1 # No error
doAssert(x == 253'u8)
echo x
except OverflowDefect:
echo "overflow!!"
something() uint implies saturated arithmetic, just use int instead
uint certainly does not use saturated arithmetic - it uses wrapping (or modular) arithmetic which is useful for example when doing pointer arithmetic.
Saturated arithmetic is when values are given the max/min value add/subtract, ie saturatingAdd(uint.high, 1) == uint.high.
uint on the other hand will wrap around, ie uint.high + 1 == 0.
Finally, `carrying` operations perform wrapping arithmetic but also return a flag saying if there was an overflow - this is typically what compilers use to implement both saturating arithmetic and, for int, to raise the exception and ruin your day.
Why don't you recommend converting to these types ?
https://nim-lang.github.io/Nim/system.html#Natural https://nim-lang.github.io/Nim/system.html#Positive
import strutils
type
Natural8 = range[0 .. 255]
# Positive8 = range[1 .. 255]
{.overflowChecks: on.}
proc something() =
var input: string
if readLine(stdin, input):
echo "input > ", input
var x: Natural8 = 0'u8
try:
x -= Natural8(input.parseInt().uint8)
x -= 1 # OverflowDefect
x = x - 1 # No error
doAssert(x == Natural(253'u8))
echo x
except OverflowDefect:
echo "overflow!!"
something()
I was expecting the following to work:
type
Natural8 = range[0 .. high(uint8)] but 0 .. high(uint8) provides a type mismatch! Conversion to a int is mandatory for the slice construction to work. I was expecting the following to work:
type
Natural8 = range[0 .. high(uint8)]
but 0 .. high(uint8) provides a type mismatch! Conversion to a int is mandatory for the slice construction to work.
The range type is determined by the type of the low bound. This works:
type Natural8 = range[0.uint8 .. high(uint8)]