Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!know!zaphod.mps.ohio-state.edu!julius.cs.uiuc.edu!apple!netcom!amdcad!sun!ringworld.Eng.Sun.COM!eager From: eager@ringworld.Eng.Sun.COM (Michael J. Eager) Newsgroups: comp.lang.c Subject: Re: Is something wrong with the compiler ? Message-ID: <143014@sun.Eng.Sun.COM> Date: 26 Sep 90 02:35:53 GMT References: <884@gtenmc.UUCP> Sender: news@sun.Eng.Sun.COM Organization: Sun Microsystems, Mt. View, Ca. Lines: 35 In article <884@gtenmc.UUCP> csp@gtenmc.UUCP (Charudutta S Palkar) writes: > > Assuming that the 2's complement system is used to represent the negative > integers. I wrote the following code , and the results I got were absurd. > >C code : > > main() > { > int a; > printf(" Maxint : %d\na = %d\n", ( int )(( unsigned ) ~0 >> 1 ) , > a = ( int )(( unsigned ) ( a = ~0 ) >> 1 )); > } > > Output : > > Maxint : -1 > a = 2147483647 > >Can some complier writer tell me why this is happening ? > >csp - csp@gtenmc.UUCP > >K&R C > ANSI C The right shift operator is not clearly defined when applied to signed integers. It looks like your compiler does a logical right shift, which inserts a high order zero bit. The assignment of a = ~0 will make a = -1. When this is shifted right by one bit, and the sign bit is set to zero, a becomes MAXINT, which you then converted to unsigned and then int, neither of which change its value. -- Mike Eager