Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Checking whether float conforms to IEEE 754

Check at compile time whether the implementation’s `float` conforms to IEEE 754, separately from any storage-size or binary-format requirements.

Version: ISO C++23; implementation support may vary

Syntax

#include <limits>

constexpr bool float_is_iec559 = std::numeric_limits<float>::is_iec559;

std::numeric_limits<float>::is_iec559, from <limits>, is a static constexpr bool member of the specialization for float. Read it without call parentheses. It is true exactly when the implementation’s float conforms to ISO/IEC 60559 (IEEE 754), and false otherwise. It describes the type, not an individual value. C++23 does not require it to be true for float.

Check storage size separately. sizeof(float) == 4 means four C++ bytes, not necessarily four octets. If you require four eight-bit bytes, also check CHAR_BIT == 8 from <climits>. Use static_assert to reject a build that does not meet your requirements, or if constexpr to select an alternative path at compile time.

Even if all these checks pass, do not simply copy the in-memory bytes into a file or network packet. Specify the exact encoding (for example, IEEE 754 binary32) and byte order, then verify that the in-memory representation matches or explicitly encode the data in the required format.

Examples

#include <climits>
#include <iostream>
#include <limits>

int main() {
    constexpr bool iec559 = std::numeric_limits<float>::is_iec559;
    constexpr bool four_octets = sizeof(float) == 4 && CHAR_BIT == 8;

    if constexpr (iec559 && four_octets) {
        std::cout << "Float requirements met\n";
    } else {
        std::cout << "Float requirements not met\n";
    }
}

Result

Float requirements met

The shown output assumes the trait is `true` and `float` occupies four eight-bit bytes. Otherwise, the program prints `Float requirements not met`. The example does not serialize anything.

Related lessons

  • C++ · Lesson 17 · Advanced · Version: 3

Sources