Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Int overflow in literals
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Issac Trotts <ijtrotts@u...>
Subject: Re: [Caml-list] Int overflow in literals
On Thu, Oct 30, 2003 at 10:36:24PM +0100, Frederic van der Plancke wrote:
> 
> 
> Issac Trotts wrote:
> > 
> > On Thu, Oct 30, 2003 at 02:53:32PM +0100, Marcin 'Qrczak' Kowalczyk wrote:
> > > I understand that int overflow is not checked on arithmetic for
> > > efficiency reasons, but IMHO it would be better if it was checked
> > > at least in literals. When someone writes 10000000000, he certainly
> > > does not mean -737418240.
> > 
> > If you want to be sure that the number is correctly stored, you can use
> > Int64:
> > 
> >     Int64.of_string "10000000000"
> > 
> > Issac
> 
> That was not my problem. My problem was to be able to read a list of integers from a file and be warned in case of overflow. And to be able to rely on int_of_string for that purpose. I got hit... of course now I know, but other innocent programmers may get hit in the future as well. (Not to speak of the not-so-innocent people who wrote this nice OCaml compiler ;-)

Here's a way to do what you want, at least for numbers 
betweeen -9223372036854775808 and 9223372036854775807 :

let safe_int_of_string str =
    let i = int_of_string str in
    let i64 = Int64.of_string str in
    if i64 = Int64.of_int i then i else failwith "overflow"

# safe_int_of_string "10000000000";;
Exception: Failure "overflow".
# safe_int_of_string (string_of_int 1073741823)
    ;;
    - : int = 1073741823

-ijt 

> 
> Fr?d?ric.
> 
> -------------------
> To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
> Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
> 

-- 

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners