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?
Macros were introduced in C to express things that couldn’t be expressed well otherwise in the language. In this particular example,
INFINITYnames 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, usingstd::numeric_limits<float>::infinity()has the following advantages:infinityto denote other things without causing name clashes.std::numeric_limits<T>::infinity()can be specialised for different values ofT, and it can be used without conversion in generic contexts.For historical reasons,
infinity()is a function but this isn’t terribly important because (since it’sconstexpr) you can use it in any context in which you could use any other constant expression.Conversely, compared to
std::numeric_limits<float>::infinity(), usingINFINITYhas the following advantages: