Smallest int value that is smaller than the smallest representable int?

Viewed 93

std::numeric_limits<T>::infinity() returns 0 if T is an integral type. Is there a replacement for this function that I can use? I have a series of int variables (they could be int8, uint8, int32, uint32, int64, uint64) that could take on values anywhere between their minimum (inclusive) and maximum (inclusive) values.

I need a value that is smaller than all of these variables, and this value will be used to comparison purposes (I would be comparing whether this value is smaller than my series of int variables).

I know I could something like -std::numeric_limits<double>::infinity(), but if I were to compare my int variables with this value, the comparison would be done in FP precision, and I'm concerned about the performance implications of that. I would, ideally, like all the comparisons to be done with integers.

I think the smallest int value that we can have is std::numeric_limits<int64_t>::minimum(), so I think my question is essentially asking if we can get an integer value smaller than this?

1 Answers

You can define your own minus infinity constant that compares less than any other value.

This is less tedious with C++20's three way comparator (aka spaceship), but feasible in previous versions:

#include <compare>

struct minus_infinity_t {} constexpr minus_infinity;

auto constexpr operator<=> (minus_infinity_t, minus_infinity_t)
{ return std::weak_ordering::equivalent; }
template<class T> auto constexpr operator<=> (T, minus_infinity_t)
{ return std::weak_ordering::greater; }
template<class T> auto constexpr operator<=> (minus_infinity_t, T)
{ return std::weak_ordering::less; }


int main()
{
    constexpr int n = 0;
    constexpr long long k = 1;
    constexpr double l = 2;
    
    static_assert(n > minus_infinity);
    static_assert(k > minus_infinity);
    static_assert(l > minus_infinity);
    
    static_assert(minus_infinity <= n);
    static_assert(minus_infinity <= k);
    static_assert(minus_infinity <= l);
}

Live demo


Improvement ideas:

  • Restrict what T can be with concepts
  • Define a positive infinity
  • Define a negative and positive zero
Related