On Tue, 25 Jan 2005 09:27:52 +0000, Ro wrote:
> On Mon, 24 Jan 2005 23:30:17 +0100, Herbert Kleebauer <(EMail Removed)>
> wrote:
>>Ro wrote:
>>
>>> I think that a complex language (like C)
>>> where is possible to write
>>
>>> z= x*y+x+y;
>>
>>> has the change to cause error on overflow in the last expression
>>> but asm not
>>
>>There can't be an overflow in a modulo 2**n arithmetic.
>
> So how do you call (unsigned char)64 * (unsigned char 4)?
If you interpret (unsigned char)64 * (unsigned char)4 you will get the
result 256 because unsigned char operands would (typically) be pronoted to
int before the operation is performed and the result of the operation
would then also have type int.
But speaking in mathematical terms in a modulo 256 number system the
result of 64 * 4 is 0. This is not because of overflow, it is simply the
natural result in that mathematical system. Consider the simpler case of
255+1 In modulo 256 arithmetic the number after 255 is 0, there is no
boundary as such to "overflow".
> #include <stdio.h>
> #include <stdlib.h>
>
> int main(void)
> {unsigned char i=64,j=4,k;
> unsigned int a1,a2,m1,m2, m3;
>
> a1=k=i+j; a2=i+j;
> m1=k=i*j; m2=i*j;
> m3=(unsigned char)(i*j);
In this case the code is converting an int value of 256 back to unsigned
char. To do that we apply C's rules for converting out of range values.
This happens to be consistent, also producing a zero result where
CHAR_BIT is 8.
> printf("a1=%d a2=%d m1=%d m2=%d m3=%d\n",
> a1, a2, m1, m2, m3);
> return 0;
> }
>
> with output here:
> a1=68 a2=68 m1=0 m2=256 m3=0
>
> (it seems in m1 the result of overflow)
> but what I don't understand is why m2=256
>
> if i=64 is uchar and j=4 is uchar => i*j=256=0 in uchar so why here
> m2=256 ? Why m2!=m3?
> [So m2=((unsigned)i)*j; and not m2=(unsigned)(unsigned char)(i*j);]
The multiplications are performed in int arithmetic. Without the
assignment to k as in the case of m1, or the case in m3, the result isn't
shorted back to character width.
Lawrence
