assigning an integer to the negation of a cast of a short to a u_short

Robert Lake lake at alberta.UUCP
Tue Dec 20 04:13:37 AEST 1988


Now that I have your attention with the title of the article (which is what
this article is about), let us consider the following program:

	main() {
		int i;
		short j = 1;
		i = -(unsigned short)j;
		printf("i=%d\n", i);
	}

If I run this program on a VAX 11/780 using 4.3 BSD, I obtain -1 as the
answer.  However, if I run this on a SUN using SUN OS 3.5, I obtain 65535
as the answer.  Who is right?  I personally think 65535 should be the
answer, and the 4th line of the program should read:

		i = -(int)((unsigned short)j);

if it is to perform the same function with all C compilers.

In case anyone is wondering why I would want to do anything like this,
you will find the following statement in the file netinet/ip_input.c in
the 4.3 kernel:

		i = -(u_short)ip->ip_len;

which, I think, should really read:

		i = -(int)((u_short)ip->ip_len);

Opinions anyone?
					Rob Lake (alberta!lake)
					University of Alberta



More information about the Comp.lang.c mailing list