Newsgroups: comp.lang.c
Path: utzoo!henry
From: henry@zoo.toronto.edu (Henry Spencer)
Subject: Re: Type conversion within arithmetic expressions. What does ANSI say ?
Message-ID: <1990Oct5.171058.27447@zoo.toronto.edu>
Organization: U of Toronto Zoology
References: <6584@castle.ed.ac.uk>
Date: Fri, 5 Oct 90 17:10:58 GMT

In article <6584@castle.ed.ac.uk> elee24@castle.ed.ac.uk (H Bruce) writes:
>How should the following code fragment compile ?
>
>unsigned char x,y;
>unsigned short int z;
>z=x*y;
>
>According to the ANSI standard, if the result of x*y exceeds 255, 
>will all 16 bits be copied to z  or only the lower 8 ?
>(i.e if x=2 and y=200 does z=400 or 400%256 ?)
>
>I have a C compiler for the 8051 which does not copy the upper byte across
>even if z=x*y is replaced with z=(unsigned short int)x*y.

The first question you should ask is "how big is `unsigned short' on the
8051?".  If it's 8 bits, then your question is answered.  This would not
be an ANSI-standard implementation, since ANSI C requires >=16 bits for
shorts of all kinds, but there are lots of non-ANSI and semi-ANSI compilers
out there, especially for cruddy little 8-bit machines that have trouble
supporting 16-bit and 32-bit arithmetic efficiently.

Assuming that `unsigned short' is indeed 16 bits, your compiler is exceeding
its authority here.  `unsigned char' turns into some sort of `int' (details
slightly implementation-dependent) immediately on use in an expression, so
the value of that multiplication is definitely at least 16 bits, and should
be copied as such.  A compiler can shorten such operations only if it can
guarantee that this will not affect results... not true in this case.
-- 
Imagine life with OS/360 the standard  | Henry Spencer at U of Toronto Zoology
operating system.  Now think about X.  |  henry@zoo.toronto.edu   utzoo!henry
