jeudi 7 février 2019

floating point exception is thrown when casting double to int

Consider this code:

#include <iostream>
#include <climits>
#include <fenv.h>

int main()
{
    feenableexcept(FE_INVALID);
    double d = INT_MAX * 2.0f;
    int i = (int)d; // it throws here fpe exception and terminates. Why ?

    std::cout << i << std::endl;

    return 0;
}

First thing that can be noticed here is that casting double to an int causes overflow of the temporary value (it is more than INT_MAX), which is of course in general undefined behavour.

But I'm more concerned about the fact that FPE exception here can be trapped by passing FE_INVALID constant flag to the feenableexcept function.

From the cpp_reference I can see that FE_INVALID has nothing to do with overflowing at all.

Why then integer overflowing here causes fpe exception ?

Is that because of the nature of UB ?

Aucun commentaire:

Enregistrer un commentaire