Home > Net >  Conventions for using std::feclearexcept
Conventions for using std::feclearexcept

Time:12-02

Is there any convention for using std::feclearexcept? In the examples you usually see, this is called before an operation is executed that might trigger a floating point exception. This seems a safe thing to do.

But should you also call std::feclearexcept after you have detected and handled an error, so that the error state does not persist throughout the rest of the program's execution?

If you would always call std::feclearexcept before checking for floating point exceptions, and if you would always check all operations that could trigger such exceptions, then this would be redundant. But these are a lot of ifs and an unlikely situation in real software, at least from my experience.

CodePudding user response:

Simlar in reasoning to (re-)setting errno only before you do a specific operation and intend to check errno afterwards.

There might be conditions under which errno, or the floating point exception flags, are set that you are not aware of. You don't know where exactly they happened or what they mean semantically. You are not equipped to handle a situation of "uh, there was an overflow somewhere in the past but I don't know what it means".

Thus, you reset errno / call std::feclearexcept right before you execute a specific operation where you want to know the exact result / error condition, and do know how to handle it.

Resetting the error flags after that operation serves no purpose.

  • Related