Re: initializing int to a number bigger than INT_MAX





Michael Coyne wrote:
> On Tue, 12 Apr 2005 09:29:35 -0700, vikky@xxxxxxxxx said to the parser:
>
>
>>hi all,
>>Out of sheer curosity, I decided to initialize an integer with a number
>>bigger than INT_MAX, however I still am not able to justify its output.
>>Here is the program :
>>
>> int t=0xFFFFFFFFFFFFFFFFDABC;
>
>
> First of all, this is in fact *smaller* than INT_MAX. What you've
> written is a negative number, as you're using a signed int. All the
> extra leading Fs, above and beyond the 32-bit limit of your architecture,
> in binary terms, are leading ones, which can "safely" be "dropped" and
> still yield the same 2s-complement number in a "lower int-sized" machine,
> assuming the meaningful bits of the number are small enough to fit.
>
> Hmmm, I didn't explain that very well, but...

No, indeed: Much of what you wrote was incorrect.

To begin with, the hexadecimal constant is a large
*positive* number. In fact, all numeric[*] constants in C
are non-negative. The problems here are (1) that the big
hex constant may be too large for any integral data type
supported by the implementation, and (2) even if that's
not the case, it may be bigger than INT_MAX.

Case 1 may apply even though the compiler didn't
complain; I can't find anything in the Standard that seems
to require a diagnostic for out-of-range constants. If
case 1 applies, we really can't tell for sure what happened,
but it looks like the compiler may have mangled the value
(along the lines you describe, and that part of your answer
was correct -- for two's complement machines, anyhow).

If it's case 2, initialization is "as if" by conversion
of the very large value to `int'. Converting an out-of-range
value to `int' produces an implementation-defined result (or
raises an implementation-defined signal). On two's complement
machines it is likely that the implementation-defined result
will be "chopped" in the way you describe, but this is not
guaranteed by the Standard.

[*] The only negative constants I can think of are enum
values specifically declared as negative, and character or
wide-character constants involving "extra" characters not
in the basic execution set (and even then only if `char' or
`wchar_t' is signed). Constants that "look like" numbers
are non-negative.

--
Eric.Sosman@xxxxxxx

.



Relevant Pages