Search code examples
c++hlsl

Is maximum float + x defined behavior?


I did a quick test using the following:

float x = std::numeric_limits<float>::max();
x += 0.1;

that resulted in x == std::numeric_limits::max() so it didn't get any bigger than the limit.

Is this guaranteed behavior across compilers and platforms though? What about HLSL?


Solution

  • Is this guaranteed behavior across compilers and platforms though?

    No, the behavior is undefined. The standard says (emphasis mine):

    5 Expressions
    ....
    If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]

    As @user2079303 mentioned, in practice we can be less restricted:

    it is not undefined if std::numeric_limits<float>::has_infinity. Which is often true. In that case, the result is merely unspecified.