I was reading Setting an int to Infinity in C++. I understand that when one needs true infinity, one is supposed to use numeric_limits<float>::infinity()
; I guess the rationale behind it is that usually integral types have no values designated for representing special states like NaN, Inf, etc. like IEEE 754 floats do (again C++ doesn't mandate neither - int
& float
used are left to the implementation); but still it's misleading that max > infinity
for a given type. I'm trying to understand the rationale behind this call in the standard. If having infinity
doesn't make sense for a type, then shouldn't it be disallowed instead of having a flag to be checked for its validity?
The function numeric_limits<T>::infinity()
makes sense for those T
for which numeric_limits<T>::has_infinity
returns true
.
In case of T=int
, it returns false
. So that comparison doesn't make sense, because numeric_limits<int>::infinity()
does not return any meaningful value to compare with.
0
or false
. –
Nephritis numeric_limits<int>::infinity()
? –
Quenelle If you read e.g. this reference you will see a table showing infinity to be zero for integer types. That's because integer types in C++ can't, by definition, be infinite.
Suppose, conversely, the standard did reserve some value to represent inifity, and that numeric_limits<int>::infinity() > numeric_limits<int>::max()
. That means that there would be some value of int
which is greater than max()
, that is, some representable value of int
is greater than the greatest representable value of int.
Clearly, whichever way the Standard specifies, some natural understanding is violated. Either inifinity() <= max()
, or there exists x such that int(x) > max()
. The Standard must choose which rule of nature to violate.
I believe they chose wisely.
numeric_limits<int>::infinity()
- which is possible with a bit of metaprogramming. –
Russi has_infinity
would be true, and hence it's the programmer who has to add another exception to his mental model. This is exactly what makes C++ expert-friendly and complex for the Joe coder. –
Coyle numeric_limits<int>::infinity()
returns the representation of positive infinity, if available.
In case of integers, positive infinity does not exists:
cout << "int has infinity: " << numeric_limits<int>::has_infinity << endl;
prints
int has infinity: false
© 2022 - 2024 — McMap. All rights reserved.
numeric_limits<int>::has_infinity
istrue
? If it's not, then the standard doesn't requireinfinity()
to be meaningful. – Premaxillahas_infinity()
trying out the above line will shoot his foot nice and square; it seems unintuitive. – Coylehas_infinity()
, didn't opt for not defininginfinity()
for such types? – Coylehas_infinity()
, it is justhas_infinity
. It is not a function. – Russi