[Haskell-beginners] Overflow when reading C types
Isaac Dupree
ml at isaac.cedarswampstudios.org
Tue Dec 3 02:40:01 UTC 2013
On 12/02/2013 07:14 PM, Daniel Fischer wrote:
> On Monday 02 December 2013, 18:14:20, Isaac Dupree wrote:
>> C conversions from floating-point to signed or unsigned integral also
>> saturate.
>
> Not really. Clause 6.3.1.4 is quite explicit:
>
> "When a finite value of real floating type is converted to an integer type
> other than _Bool, the fractional part is discarded (i.e., the value is
> truncated toward zero). If the value of the integral part cannot be
> represented by the integer type, the behavior is undefined."
>
> and adds a footnote to make it unmistakeably clear that the remaindering
> operation need not be carried out when the target type is unsigned.
Whoops! Thank you for correcting me.
>> Unsigned types being Z/nZ is mathematically sound, but C is not very
>> dedicated to this interpretation.
>
> It's mandated in 6.2.5 (9),
>
> "A computation involving unsigned operands can never overflow, because a
> result that cannot be represented by the resulting unsigned integer type is
> reduced modulo the number that is one greater than the largest value that can
> be represented by the resulting type."
Yes, indeed, C unsigned arithmetic *is* Z/nZ and that is lovely (when
you want it, at least).
My point there was that some functions/operations specified by the C
standard that are related to unsigned types, like conversion from
strings (strtoul()) and floats (casting), aren't modulo 2^n. I see
that's a weak point since each of those only differ from modulo in error
conditions (errno set, or undefined behaviour). If C was as good as(?)
Haskell it might use modulo for those conversions too.
-Isaac
More information about the Beginners
mailing list