Re: Shifting: what's going on?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Facundo Ciccioli writes:
 > FaQ
 > 
 > 2007/3/29, Andrew Haley <aph@xxxxxxxxxx>:
 > > Facundo Ciccioli writes:
 > >  >
 > >  > This is obviusly not urgent, since the first code is perfectly
 > >  > acceptable and applicable to what I am doing, but I just got curious.
 > >
 > > This is an arithmetic overflow, and is explicitly undefined.  One
 > > result is as good as any other.  What do you expect the code to do?
 > >
 > I expect to get a 1 in the s-th bit of a, and zeroes in all other
 > bits. I don't know why you say that's an arithmetic overflow, if
 > unsigned long long is 64 bits long and it has a 63-th bit (the last
 > one).
 > 
 > Anyway, Rupert Wood comment works, thanks a lot.

So, even after Rupert Wood's explanation, you still don't realize
that you had written an arithmetic overflow?  Let's have a look at
your code:

int main() {
   unsigned long long a;
   unsigned s= 63;

   a= (1 << s);

   return 0;
}

This expression is a 32-bit signed integer constant 1 shifted left 63
places, which overflows:

   (1 << s);

You then assign the result of this overflow to the 64-bit signed
integer variable a:

   a= (1 << s);

Andrew.

-- 
Red Hat UK Ltd, Amberley Place, 107-111 Peascod Street, Windsor, Berkshire, SL4 1TE, UK
Registered in England and Wales No. 3798903

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux