Path: utzoo!attcan!uunet!motcid!benyukhi From: benyukhi@motcid.UUCP (Ed Benyukhis) Newsgroups: comp.lang.c Subject: Re: Is something wrong with the compiler ? Summary: Compiler implementation specific (arith., logical shifts & sign extensions) Message-ID: <4738@navy19.UUCP> Date: 27 Sep 90 17:09:31 GMT References: <884@gtenmc.UUCP> <143014@sun.Eng.Sun.COM> Organization: Motorola Inc., Cellular Infrastructure Div., Arlington Heights, IL Lines: 30 In article <143014@sun.Eng.Sun.COM>, eager@ringworld.Eng.Sun.COM (Michael J. Eager) writes: > In article <884@gtenmc.UUCP> csp@gtenmc.UUCP (Charudutta S Palkar) writes: > > 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 ? > > 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. On the contrary, it looks like his compiler does an arithmetic shifts which sign extends i.e. fills vacated bits with the original sign bit. This problem really concerns the "right shifts on signed operands". The language permits the shift to be implemented as an arithmetic shift operation or a logical shift (fill vacated bits with 0's). The choice is left to the compiler writer. "When the left operand of >> is an unsigned type, C mandates a logical shift". Thus declaring a variable to be an unsigned type yields uniform behavior. Ed Benyukhis