Is a whole number float divided by itself guaranteed to be 1.f?

If I write:

int x = /* any non-zero integer value */;
float y = x;
float z = y / y;

Is z guaranteed to be exactly 1.f ?


If your C++ implementation uses IEEE754 then yes, this is guaranteed. (The division operator is required to return the best possible floating point value).

The only exceptions for y / y, in general, not being 1.f are the cases when y is NaN, +Inf, -Inf, 0.f, and -0.f, or if you are on a platform where int is so wide that certain instances of it cannot be represented in a float without that float being set to +Inf or -Inf1. Setting aside that final point, in your case that means that int x = 0; will produce the only exception.

IEEE754 is extremely common. But to check for sure, test the value of

std::numeric_limits<float>::is_iec559;

1A platform, for example, with a 128 bit int and an IEEE754 32 bit float would exhibit this behaviour for certain values of x.


No, not in all cases, even for IEEE754.

For example, with int x = 0;, you'll get NaN. (Live)