Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!umcp-cs!chris From: chris@umcp-cs.UUCP (Chris Torek) Newsgroups: net.lang.c Subject: Re: Any GOOD reason for C's behaviour in this example? Message-ID: <2566@umcp-cs.UUCP> Date: Wed, 23-Jul-86 06:17:23 EDT Article-I.D.: umcp-cs.2566 Posted: Wed Jul 23 06:17:23 1986 Date-Received: Thu, 24-Jul-86 01:31:25 EDT References: <1080@ttrdc.UUCP> Reply-To: chris@maryland.UUCP (Chris Torek) Organization: University of Maryland, Dept. of Computer Sci. Lines: 47 Summary: No: nor is your compiler correct In article <1080@ttrdc.UUCP> levy@ttrdc.UUCP (Daniel R. Levy) writes: >I recently came across a situation in C which caused me to do a double >take, at least until I dug out my trusty, dogeared K&R: > >main() >{ > unsigned short a, b; > int i; > a=4; > b=5; > i = ( (int) a) - ( (int) b); > (void) printf("%d\n",i); > return 0; >} > >... I was half expecting that casting the unsigned short values to >ints would make them be treated as ints in an expression which takes a >difference between two of them. [But] ... this little program produces >... 65535. > >Now deep in the bowels of K&R there is a paragraph explaining that >indeed this is what is supposed to happen ... Where? K&R, p. 42: The precise meaning of a cast is in fact as if {\it expression} were assigned to a variable of the specified type, which is then used in place of the whole construction. Therefore, unsigned short us1, us2; int i1, i2; int r1, r2; us1 = 4; us2 = 5; r1 = (int)us1 - (int)us2; i1 = us1; i2 = us2; r2 = i1 - i2; should produce the same values in `r1' and `r2'. Indeed, the 4.3BSD C compiler produces -1 for both. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 1516) UUCP: seismo!umcp-cs!chris CSNet: chris@umcp-cs ARPA: chris@mimsy.umd.edu