Date: Fri, 25 Nov 1994 21:41:56 -0500 (CDT) From: Aaron Ucko Subject: Re: -1441992/4 = 1073381326 To: OKRA AT max DOT tiac DOT net Cc: djgpp AT sun DOT soe DOT clarkson DOT edu Organization: Rockhurst College; Kansas City, MO > 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 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 it should. Since y is unsigned and x is `only' a long, x gets cast to an unsigned before the division. (although actually it's not quite so simple; the compiler chooses `unsigned long' as the data type large enough to hold both numbers, so they both get cast to that, so a DIV is used. Why not just make y an ordinary signed integer? --- Aaron Ucko (ucko AT vax1 DOT rockhurst DOT edu; finger for PGP public key) -=- httyp! -=*=-Just because you're paranoid doesn't mean they aren't out to get you.-=*=- Geek code 2.1 [finger hayden AT vax1 DOT mankato DOT msus DOT edu for explanation]: GCS/M/S d(-) H s g+ p? !au a-- w+ v+ C++(+++)>++++ U-(S+)>++++ P+ L>++ 3(-) E-(----) !N>++ K- W(--) M-(--) V(--) po-(--) Y+(++) t(+) !5 j R G tv--(-) b+++ !D(--) B--(---) e>++++(*) u++(@) h!() f(+) r-(--)>+++ n+(-) y?