digitalmars.D.learn - exception and integer overflow
- Sebastian Philipp (24/24) Apr 15 2007 Hello,
- Thomas Kuehne (41/64) Apr 15 2007 -----BEGIN PGP SIGNED MESSAGE-----
Hello, is it possible to check for integer overflows? $ cat test.d; dmd -w *.d; ./test import std.stdio; int main(char[][] args) { uint i = 0, j = uint.max;; writefln("i = ",i, ";j = ",j); try { --i;++j; } catch (Exception e) { writefln("exception!"); } writefln("i = ",i, ";j = ",j); return 0; } gcc test.o -o test -m32 -lphobos -lpthread -lm i = 0;j = 4294967295 i = 4294967295;j = 0 Where is my fault? Sebastian
Apr 15 2007
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Sebastian Philipp schrieb am 2007-04-15:Hello, is it possible to check for integer overflows?Yes.$ cat test.d; dmd -w *.d; ./test import std.stdio; int main(char[][] args) { uint i = 0, j = uint.max;; writefln("i = ",i, ";j = ",j); try { --i;++j; } catch (Exception e) { writefln("exception!"); } writefln("i = ",i, ";j = ",j); return 0; } gcc test.o -o test -m32 -lphobos -lpthread -lm i = 0;j = 4294967295 i = 4294967295;j = 0 Where is my fault?The code is behaving as designed (silent overflow). One way to throw an exception if an uint addition overflows can be found below: Thomas -----BEGIN PGP SIGNATURE----- iD8DBQFGIpVjLK5blCcjpWoRAgoAAJ9E9OyyYVJSNuxb2HWZ358jbgj3WgCdEQff mRFP+ygvO7HQewMbUIraT20= =RmmZ -----END PGP SIGNATURE-----
Apr 15 2007