From: rafael AT alpha DOT coe DOT ufrj DOT br (Rafael Gustavo da Cunha Pereira Pinto) Subject: Re: -1441992/4 = 1073381326 To: OKRA AT max DOT tiac DOT net (Kimberley Burchett) Date: Mon, 28 Nov 94 8:28:14 GMT-3:00 Cc: djgpp AT sun DOT soe DOT clarkson DOT edu (djgpp Mailing List) Hi Kim, > > This program: > > int main() { > > long x = -1441992; > unsigned y = 4; > > printf("%d / %d = %d\n",x,y,x/y); > } > > Spits this out: > > -1441992 / 4 = 1073381326 > The answer is easy... There's no problem when the compiler optimizes it. The problem is that when you divide anything by an unsigned value, the compiler casts the answer to the unsigned type! > > The division is done at compile time if I compile with optimizations on. > A more complex program where the division can't be done at compile time > gets the same result doing the division at run time. Can anyone tell me > why? As far as I know, even in the strange world of CPU math, overflows > can't account for this result. The only thing I can think of is that the > compiler is using DIV instead of IDIV (however, in this case, dividing by > 4, it shouldn't use any DIV). The funny math only shows up when x is > negative (never tried y negative...). It doesn't matter whether I'm using > the C or the C++ compiler. Yes, you're right. The compiler is using DIV, since it's an unsigned value that should be returned. > For Those Who Care: I found this little glitch when for some reason a > program I was trying to write kept making little "birds" zip off the > screen - I was using this to calculate delta x's and y's. Two or three > hours of debugging and now I'm a lot more comfortable with gdb. > Kimberley > BTW, you work with computer graphics, don't you? I'd like to exchange some ideas with you. Regards, Rafael Pinto ---------------------------------------------------------------------------- Rafael Gustavo C. P. Pinto | Phone: 55-21-598-2454 Software Engineer - CEPEL | Fax: 55-21-260-1340 Electric Power Research Center | P.O. Box 2754 | E-Mail:rafael AT acsi DOT cepel DOT br Rio de Janeiro, RJ 20.001 - Brasil | rafael AT fund DOT cepel DOT br ----------------------------------------------------------------------------