Any GOOD reason for C's behaviour in this example?

Chris Torek chris at umcp-cs.UUCP
Wed Jul 23 20:17:23 AEST 1986


In article <1080 at ttrdc.UUCP> levy at 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 at umcp-cs		ARPA:	chris at mimsy.umd.edu



More information about the Comp.lang.c mailing list