Search code examples
c++exceptionsignalsdivide-by-zero

NaN vs floating point exception?


I came across a weird behavior in C++.

Running the following line results in a floating point exception:

long double res = 0 / 0 * 100;

However, running the following lines results with the variable res being printed out as a -nan:

long double res = static_cast<long double>(0) / 0 * 100;
std::cout << res << std::endl;

Can anyone clarify why this happens? Under what conditions does a calculation evaluate to 'nan' and when will it raise a division by 0 exception as a "floating point exception"?


Solution

  • The subexpression 0 / 0 is performing integer division since both operands have integer type. Because there are no NaNs in integer types, this will typically generate a floating point exception.

    In contrast, static_cast<long double>(0) / 0 performs floating point division since one operand has floating point type. So on implementations that support NaN, this will typically result in NaN on those implementations.

    Note that strictly speaking division by zero is undefined behavior, although the above is what you'll most likely experience.