c++bitflags

Can return value of fetestexcept contain multiple flags?


Can the result of std::fetestexcept return multiple bits set, or does it only ever return a single bit?


Solution

  • It can return an int with up to as many bits set as you provided in the argument to std::fetestexcept. If you for example provided FE_ALL_EXCEPT as an argument, it may return an int with a combination of ...

    FE_DIVBYZERO
    FE_INEXACT
    FE_INVALID
    FE_OVERFLOW
    FE_UNDERFLOW
    

    ... bitwise ORed together. To check for a certain bit, just do a bitwise AND with the constant you'd like to check:

    if (std::fetestexcept(FE_ALL_EXCEPT) & FE_OVERFLOW) {
        std::cout << "the overflow bit was set\n";
    }
    

    Of course, if you only provide a constant with a single bit set, like FE_OVERFLOW, it will only return an int with zero or one bit set and then you don't need the bitwise AND after the call:

    if (std::fetestexcept(FE_OVERFLOW) {
        std::cout << "the overflow bit was set\n";
    }