Exception when casting doubles to ints

alan buckley alan_baa at hotmail.com
Fri Jan 7 03:26:38 PST 2005


>Nick Burrett wrote:
>alan buckley said:
> >>John Tytgat wrote:
> >>
> >>In message <BAY101-F254E3ED3F8DDFE11900C51F0930 at phx.gbl> you wrote:
> >>
> >> > It appears that when a double that is larger than the maximum
> >> > int is cast to an int a floating point exception occurs. On cygwin
> >> > you do not get an exception, and as the code where I found the
> >> > problem was in lua I suspect other linux/unix variations also do not
> >> > raise an exception. Can anyone confirm the unix behaviour?
> >> >
> >> > If this is the case should the RISC OS gcc match what unix does?
>
>On x86/Linux, no error is reported and k = -2147483648.

This is the same result as on cygwin.

>
> >>Actually I don't mind this being the default behaviour because it is
> >>something pretty undefined what int value you would have if no exception
> >>would be raised.
> >
> > The default behaviour does make sense to me as well. However it does
> > appear that it may be different from the behaviour generated by GCC on
> > other machines.
>
>True, but I think this it is a misconception to assume that the
>environment of RISC OS should exactly match that of Unix.  Though we try
>to achieve it, simulating a floating-point environment is not necessarily
>so easy.

Fair enough. This is why it was a question rather than a bug report:-)

>
>Perhaps UnixLib should be setting the FPA co-processor state flags on
>startup correctly, but this needs to be investigated in more detail to
>ensure we conform with the C standards rather than the Unix environment.

This seems sensible to me.

>
> >>
> >>But I think your question is around the header fenv.h
> > Have I misread the documentation? If so, can you show me the code I
> > need to add to a program?
>
>I think John's referring to the 'fesetenv' function.  However our
>implementation only sets the flags to their default, which isn't really
>helpful here.
>
> > If not, is there any other routine I can add to the program to modify 
>how
> > casting from double to int is handled.
>
>Does this problem not actually point at a bug ? The idea of overflowing an
>integer sounds problematic and reminds me of the Ariane 5 spacecraft
>disaster. :)
>

The code is in the lua library and (apart from throwing exceptions) looks 
fairly
safe as it then compares the cast integer value to the original floating 
point
value to determine if it really is an integer. As the orignal number is 
outside
the range of an integer this test will always be false as expected whatever
value the integer is set to.

The only thing I'd say in defence of this behaviour is that you can cast an
oversize int to a char and not get an exception so why should floats be
different.

I've patched the code to get around this for my build.

Thanks for your help,
Alan





More information about the gcc mailing list