Path: utzoo!attcan!uunet!oddjob!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Puzzle on unsigned promotions Message-ID: <12251@mimsy.UUCP> Date: 30 Jun 88 20:02:08 GMT References: <736@vsi.UUCP> Distribution: comp Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 74 In article <736@vsi.UUCP> friedl@vsi.UUCP (Stephen J. Friedl) writes: >... unsigned- vs value-perserving rules ... [and the following code, reproduced without > to fool inews; slightly compressed] main() { unsigned short sval; long lval1, lval2; sval = 0xffff; lval1 = -sval; lval2 = -(unsigned short)0xffff; printf("lval #1 = %ld #2 = %ld\n", lval1, lval2); } Well, first, no matter what, you should get the same value in lval1 and lval2. A cast is equivalent to assignment to an unnamed temporary, so the second assignment is like writing { unsigned short tmp; tmp = 0xffff; lval2 = -tmp; } which is semantically identical to `lval1 = -sval'. Now, to answer `what should I get', you need to know the relative sizes of short, int, and long (and their unsigned variants). sval = 0xffff; sizeof(short) = 2; sizeof(int) = sizeof(long) = 4: lval = -sval: Old rule: unsigned stays unsigned First turn sval into an rvalue: (u_short)0xffff is extended to (u_int), result is (u_int)0x0000ffff Next negate: result is (u_int)0xffff0001 Next convert to (signed long) by `bits-as-is' due to assignment: (long)0xffff0001 or -65535. New rule: unsigned stays unsigned if the new type does not have more bits, otherwise unsigned becomes signed: First turn sval into an rvalue: (u_short)0xffff is extended to (signed int), result is (int)0x0000ffff. [note that the bit pattern produced by both rules is always identical; the difference is in the interpretation of that bit pattern---signed vs unsigned] Next negate: result is (int)0xffff0001 Convert to long by `bits-as-is': (long)0xffff0001 or -65535. >The normal answer I get is: > > lval #1 = -65535 #2 = -65535 which is correct. >but on the HP9000 I see: > > lval #1 = 1 #2 = -65535 Your HP9000 compiler is broken. >Please email, I'll summarize and post. Oops :-) -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris