c++stlconventionsinfinity

Ways to represent float infinity in C++


I want to express floating-point infinity in C++ for my program. I came across two ways to achieve this: using INFINITY and std::numeric_limits<float>::infinity().

Both options seem to work, but I'm unsure which one is the better choice. On one hand, INFINITY is a simple macro defined in math.h, making it easy to use. On the other hand, std::numeric_limits<float>::infinity() is a function from <limits> and is part of the C++ STL, which seems to be a conventional way.

In summary:

Should I use INFINITY or std::numeric_limits<float>::infinity() to represent floating-point infinity in my C++ program? Which one is considered a better practice, and are there any performance or portability considerations I should be aware of?


Solution

  • Macros were introduced in C to express things that couldn’t be expressed well otherwise in the language. In this particular example, INFINITY names a compile-time constant.

    C++ introduces different ways into the language that allow you to express the same things that you used to need macros for in C (in many, but not all circumstances). Regarding this particular case, C++ has a way of naming compile-time constants in various ways.

    Compared to INFINITY, using std::numeric_limits<float>::infinity() has the following advantages:

    For historical reasons, infinity() is a function but this isn’t terribly important because (since it’s constexpr) you can use it in any context in which you could use any other constant expression.

    Conversely, compared to std::numeric_limits<float>::infinity(), using INFINITY has the following advantages: