Nandan
Nandan

Reputation: 55

Are there any constants in C++ which can be used as minimum/maximum values in comparisons

Are the terms INT_MIN and INT_MAX used as constants in number comparisons as initial maximum and minimum values respectively?

Upvotes: 1

Views: 94

Answers (3)

Bob__
Bob__

Reputation: 12779

Not necessarily.

The other answers show how to use the templates available in header <limits>, but

...in number comparisons as initial maximum and minimum values...

You can actually choose the first value of a range.

See e.g. one of the possible implementations of std::max_element shown at https://en.cppreference.com/w/cpp/algorithm/max_element (comments mine):

template<class ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last)
{
    if (first == last) return last;     //     The range is empty

    ForwardIt largest = first;          // <-- Start with the first one
    ++first;
    for (; first != last; ++first) {
        if (*largest < *first) {
            largest = first;
        }
    }
    return largest;
}

Upvotes: 0

gsamaras
gsamaras

Reputation: 73384

Yes, std::numeric_limits.

Example:

// numeric_limits example
#include <iostream>     // std::cout
#include <limits>       // std::numeric_limits

int main () {
  std::cout << std::boolalpha;
  std::cout << "Minimum value for int: " << std::numeric_limits<int>::min() << '\n';
  std::cout << "Maximum value for int: " << std::numeric_limits<int>::max() << '\n';
  std::cout << "int is signed: " << std::numeric_limits<int>::is_signed << '\n';
  std::cout << "Non-sign bits in int: " << std::numeric_limits<int>::digits << '\n';
  std::cout << "int has infinity: " << std::numeric_limits<int>::has_infinity << '\n';
  return 0;
}

Possible output:

Minimum value for int: -2147483648
Maximum value for int: 2147483647
int is signed: true
Non-sign bits in int: 31
int has infinity: false

Upvotes: 6

velmafia
velmafia

Reputation: 26

std::numeric_limits provide you what you are looking for (and many more).

Example for INT_MIN/INT_MAX:

#include <iostream>
#include <limits>

int main() {
    std::cout << "int min: " << std::numeric_limits<int>::min() << std::endl; // INT_MIN
    std::cout << "int max: " << std::numeric_limits<int>::max() << std::endl; // INT_MAX

    return 0;
}

Output in my case:

int min: -2147483648
int max: 2147483647

Upvotes: 1

Related Questions