This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: float to int conversion
- From: Andrew Haley <aph at redhat dot com>
- To: "Warlich, Christof" <christof dot warlich at siemens dot com>
- Cc: "gcc-help at gcc dot gnu dot org" <gcc-help at gcc dot gnu dot org>
- Date: Mon, 22 Apr 2013 11:28:12 +0100
- Subject: Re: float to int conversion
- References: <6D83E89737156549AEA25EF9ED712C5DD11B at DEFTHW99EK1MSX dot ww902 dot siemens dot net> <5174F57B dot 4080701 at redhat dot com> <6D83E89737156549AEA25EF9ED712C5DD14A at DEFTHW99EK1MSX dot ww902 dot siemens dot net> <20130422120325 dot 6168e915 at ketmar dot no-ip dot org> <6D83E89737156549AEA25EF9ED712C5DD1A0 at DEFTHW99EK1MSX dot ww902 dot siemens dot net>
On 04/22/2013 11:12 AM, Warlich, Christof wrote:
> ketmar wrote:
>> 0x7fffffc0 can'be exactly represented in float, 'cause there is some
>> bits occupied by exponent. so it is rounded so some other number, which
>> is unfortunately too big to be converted to int. therefore conversion
>> triggers undefined behavior.
>
> Yes, that's what I suspected after I tried Andrew's example.
>
>> change float to double and everything will be fine.
>
> I guess that only shifts the problem to (much) higher numbers.
>
> After all, this reminds be a bit of a hack lawver: A legal loophole
> shamelessly capitalizing upon ;-). At least, it violates the golden
> principle of "least surprise", being said to be an essential part of
> good software design.
What do you think the conversion should do in this case? I find
the current behaviour to be the least surprising.
> Anyhow, as I really need to deal with such situations: Is there a way
> to catch such conversion errors without cluttering the code with checks
> that test if still being within the range of a conversion or not? Skimming
> the paper linked by David suggests that it should be possible to
> install trap handlers for this purpose. Does anyone know how to do this
> with gcc?
Just define your own conversion function. Any program that tries to
convert an out-of-range value and then uses the result is buggy anyway.
Andrew.