Are the terms INT_MIN and INT_MAX used as constants in number comparisons as initial maximum and minimum values respectively?
Are there any constants in C++ which can be used as minimum/maximum values in comparisons
92 views Asked by Nandan At
3
There are 3 answers
1
On
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
0
On
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;
}
Yes,
std::numeric_limits.Example:
Possible output: