Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Re: [Caml-list] Runtime overflow and what to do
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <xavier.leroy@i...>
Subject: Re: [Caml-list] Runtime overflow and what to do
> So it is not easy, perhaps even impossible if the processor doesn't set a
> flag .

It is possible, but slow and not pretty!  For example, here is Caml
code that performs integer addition and detects overflows:

exception Integer_overflow

let no_overflow_add a b = 
  if (a lxor b) lor (a lxor (lnot (a+b))) < 0  (* no kidding! *)
  then a + b
  else raise Integer_overflow

Multiplication is left as an exercise for the readers :-)

My advice would be to use bignums; they are a bit slower, but at least
you get the exact result in all cases.

- Xavier Leroy
To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: