Is something wrong with the compiler ?

Michael J. Eager eager at ringworld.Eng.Sun.COM
Wed Sep 26 12:35:53 AEST 1990


In article <884 at gtenmc.UUCP> csp at 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 at 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



More information about the Comp.lang.c mailing list