On 22 April 2013 11:12, Warlich, Christof <christof.warlich@xxxxxxxxxxx> 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. > > 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? > > Thanks for all your help so far, > > Chris It depends what you mean by "catching errors". As far as rounding is concerned you won't get an exception, or a detectable error such as a NaN. Whenever you're doing numerical processing you really need to look at what range of values you're dealing with and what level of accuracy is required (and what is achievable). If you're going to be handling widely varying values (e.g. E20 and E-20 in the same calculation) you'll have to be aware of that and deal with it sensibly. Also, don't expect to be able to get more significant digits than a float or double can actually hold. Regards, David