[net.lang.c] conversion of short to unsigned it - more

wescott@ncrcae.UUCP (Mike Wescott) (03/26/85)

In my posting I complained that various C-compilers (SysVr2 and 4.2BSD)
as well as some others incorrectly generated code for

	unsigned short us;
	short s;

	if ((unsigned int)s == us) printf("OOPS\n");

The code generated for the comparison is a

	cmpw	_s, _us

No conversion. I claim s should be sign extended, us zero padded and 
a cmpl done.

Ken Turkowski @ CADLINC writes:

>I disagree.  The "(unsigned int)" is a cast, saying that s is to be
>considered unsigned rather than signed.  It is NOT a conversion.  The
>fact that s was declared to be a "short int" is immaterial; it is of
>type int rather than float, etc.  This has the same effect as saying
>"(unsigned)", without the "int".  Int has no inherent size associated
>with it; the size of an int is machine-dependent.  If you want an int
>of a specific size, you say "short int" or "long int".
>
>I would suggest that you try the statement
>
>	if ((unsigned long int)s == us) printf("OOPS\n");
>
>instead, and see if you get the same results.  This explicitly
>specifies a size conversion.

Two points:
	1. K&R (C Ref Man, sect 7.2) says that:
	   "An expression preceeded by the parenthesized name of a
	    data type causes CONVERSION of the value of the expression
	    to the names type.  This construction is called a cast."

	   A similar phrase appears in my copy of the Draft C Standard.

	 2. "if ((unsigned long int)s == us) ..." does give me the
	   same results.  The cmpw is used.


Norman Diamond of U of Waterloo, Ontario writes:

>> 	unsinged int ui;
>> 	unsigned short us;
>> 	short s;
>>
>> 	s = -3;
>> 	us = -3;
>> 	ui = s;
>>
>> 	if ((unsigned int)s == us) printf("OOPS\n");
>>
>> prints OOPS meaning that fffffffd == 0000fffd !!!
>
>It could mean 0000fffd == 0000fffd.
>If (unsigned int) s is sometimes equivalent to (unsigned int) (int) s,
>but other times equivalent to (unsigned int) (unsigned short) s,
>then I don't think any rule is being violated.  A compiler does not
>have to be consistent in its treatment of ambiguous constructs.
>(In fact, inconsistency should be encouraged because it quickens the
>discovery of bugs.)

My comments:
	1. The construction is not ambiguous as far as C Standard and
	   K&R is concerned. 
	2. Perhaps the compiler should use rand() to pick a treatment
	   of ambiguous constructs :-)

Mike Wescott
ncrcae!wescott