Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!lll-winken!uunet!kddlab!titcca!sragwa!wsgw!socslgw!diamond!diamond From: diamond@diamond.csl.sony.junet (Norman Diamond) Newsgroups: comp.lang.c Subject: Re: checking for overflow in C Message-ID: <10237@socslgw.csl.sony.JUNET> Date: 10 May 89 05:54:44 GMT References: <13367@dartvax.Dartmouth.EDU> <10218@smoke.BRL.MIL> <13003@haddock.ima.isc.com> <939@garcon.cso.uiuc.edu> Sender: news@csl.sony.JUNET Reply-To: diamond@csl.sony.junet (Norman Diamond) Organization: /usr/lib/news/organization Lines: 35 In article <939@garcon.cso.uiuc.edu> mcdaniel@uicsrd.csrd.uiuc.edu (Tim McDaniel) writes: >Summary: A week of debugging may save you ten seconds of typing and >one minute of extra run time. Hear, hear! >C requires that unsigned arithmetic be modulo 2**n for appropriate n; >operations are not permitted to overflow. Therefore, I used unsigned >arithmetic, with a separate "int sign_bit" where necessary. >Oh, the final stores (converting the unsigned work variables to ints) >are trivial: > assert(sign_bit == 1 || sign_bit == -1); > if (sign_bit > 0) { > assert(temp <= INT_MAX); /* or SHORT_MAX or ... */ > } > else { > assert(temp <= INT_MIN); > } > actual = sign_bit * temp; If you didn't find your bug in this, you either have a brain-damaged "assert" or you didn't try very hard. Since you carefully keep temp >= 0, it's kind of hard for temp to be <= INT_MIN. -- Norman Diamond, Sony Computer Science Lab (diamond%csl.sony.co.jp@relay.cs.net) The above opinions are my own. | Why are programmers criticized for If they're also your opinions, | re-inventing the wheel, when car you're infringing my copyright. | manufacturers are praised for it?