GCC casts short to int

Andrew Haley aph@redhat.com
Thu Jun 25 14:03:00 GMT 2009


Leonitis wrote:
> Thanks for replying!
> 
> However, what I want to happen is for the product to still be a 32-bit
> integer.
> 
> My problem is that GCC takes uses the upper 16 bits of 'a' and 'b' as well
> as the lower bits. If you multiply the upper 16 bits of 'a' with the lower
> 16 bits of 'b', then you still get a number that is contained within
> 32-bits, and hence it affects the product that is added to the accumulate
> value.

Right, so you *must* prevent the overflow.  Why do you need the signed
overflow anyway?  Can't you use unsigned arithmetic?

Like this:

  unsigned int c;
  unsigned short a = 0;
  unsigned short b = 0;

  int count;

  for(count = 0; count < cycles; count++, a++, b++)
    {
      c += a * b ;
    }

Andrew.



More information about the Gcc-help mailing list