Yet another pcc botch

shirono at hcx3.SSD.HARRIS.COM shirono at hcx3.SSD.HARRIS.COM
Thu Jan 26 06:10:00 AEST 1989


In article <3310 at cbnews.ATT.COM> lvc at cbnews.ATT.COM (Lawrence V. Cipriani) writes:
> main()
> {
> 	float f, g;
> 	unsigned short u, v;
> 	short s, t;
> 
> 	u = 250; s = 250; t = 100; v = 100;
> 	f = t - s; g = v - u;
> 
> 	printf("f = %f, g = %f\n", f, g);
> }
> 
> f = -150.000000, g = 65386.000000
> 
> The correct value for g is -150.000000.

Excuse me...

Is the correct value of g REALLY -150.00?  Recall that both v and u are
unsigned short.  (v - u) should therefore be evaluated as unsigned short
and then converted to float, right?

According to K&R, (p. 183),
	Unsigned integers, declared ``unsigned,'' obey the laws of
	arithmetic modulo 2^n where n is the number of bits in the
	representation.

According to K&RII, (p. 36),

	unsigned numbers are always positive or zero, and obey the laws of
	arithmetic modulo 2^n, where n is the number of bits in the type.

So, assuming sizeof(unsigned short) is 2, then arithmetic of unsigned short
is done modulo 2^(16), or 65536.  In this case,

		(100 - 250) mod 65536	=  -150 mod 65536
					= 65386 mod 65536
					= 65386

				g = 65386.0		QED

--Roberto
______________________________________________________________________________
                               ||   Internet: shirono at ssd.harris.com
     Roberto Shironoshita      ||
      Harris Corporation       ||             ...!novavax---\
   Computer Systems Division   ||   UUCP:     ...!uunet-------!hcx1!shirono
                               ||             ...!mit-eddie-/
------------------------------------------------------------------------------
DISCLAIMER: The opinions expressed here are my own; they in no way reflect the
            opinion or policies of Harris Corporation.



More information about the Comp.lang.c mailing list