Given:
int y = - ( 2147483648 );
to which I have added parentheses and whitespace for clarity:
In article <11************ **********@h3g2 000cwc.googlegr oups.com>
bytebro <ke**********@a ah.co.ukwrote:
>On mine (Sun sparc) using gcc with exactly the same flags I get
x.c:7: warning: decimal constant is so large that it is unsigned
The constant is, indeed, unsigned (in C89/C90) on that implementation,
as others have noted. (In C99, on that implementation, the constant
has type "long long".)
The reason for this is clearer in the version with parentheses:
the constant in question is 2147483648, *not* -2147483648. The
unary "-" operator is, in C, applied later. Since 2147483648 has
type "unsigned int", the unary minus computes the "mathematic al
result" of UINT_MAX + 1 - 2147483648. Given that UINT_MAX is (on
that implementation) 4294967295, the result is 2147483648. Thus,
the assignment:
int y = - ( 2147483648 );
attempts to put 2147483648U into an "int", with compiler- and/or
hardware-dependent results.
>The program output [includes] y = -2147483648
So amusingly, it tells me the constant is unsigned, then prints it
signed.
Where's a language lawyer when you need one?!
The output comes from a printf() that prints y, using the "%d"
format. The %d format tells printf() to expect an "int" -- i.e.,
a signed integer -- and y is indeed an "int". The actual value
stored in y, when this overly-large "unsigned int" constant is
stored there, depends on the implementation, but in this case, the
stored value is in fact -2147483648, because 2147483648U has bit
pattern 0x80000000 and -2147483648 also has bit pattern 0x80000000:
this particular implementation has 32-bit two's complement
representation.
If this were a ones' complement system, 0x80000000 would represent
-2147483647 instead. In that case, the fragment:
int y = 2147483648U;
printf("y = %d\n", y);
would most likely print:
y = -2147483647;
although this would depend on additional details about the
implementation.
(Ones' complement systems are rare these days, in part because
people are more interested in getting the wrong answer as fast as
possible than in getting the right answer. :-) )
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.