is there any code to find the maximum value of integer (which is acccording to the compiler) in c/c++ like Integer.MaxValue function in java
+25
A:
In C++:
#include <limits>
then use
int imin = std::numeric_limits<int>::min(); // minimum value
int imax = std::numeric_limits<int>::max();
std::numeric_limits
is a template type which can be instantiated with other types:
float fmin = std::numeric_limits<float>::min(); // minimum positive value
float fmax = std::numeric_limits<float>::max();
In C:
#include <limit.h>
then use
int imin = INT_MIN; // minimum value
int imax = INT_MAX;
or
#include <float.h>
float fmin = FLT_MIN; // minimum positive value
double dmin = DBL_MIN; // minimum positive value
float fmax = FLT_MAX;
double dmax = DBL_MAX;
Gregory Pakosz
2009-12-06 14:00:56
Note that the floating-point `min` are the minimum *positive* value, where as the integer `min` are the minimum value. Same goes for the C macros/constants.
dalle
2009-12-31 11:29:37
exactly, thanks for the addition
Gregory Pakosz
2009-12-31 11:38:04
+4
A:
#include <climits>
#include <iostream>
using namespace std;
int main() {
cout << INT_MAX << endl;
}
anon
2009-12-06 14:01:07
I wouldn't call INT_MAX "a solution for C". It's old-school and deprecated in C++, though.
Paul Tomblin
2009-12-06 14:08:04
I think both are C++ answers. `numeric_limits<int>::max()` - works also in template contexts, but (for some unfathomable reason to me) cannot be used as a compile-time constant. `INT_MAX` - is a macro, pretty useless within template functions, but can be used as a compile-time constant.
UncleBens
2009-12-06 14:09:55
The funny thing is that numeric_limits<int>::max implementation on msvc looks like this: return (INT_MAX);
Nikola Smiljanić
2009-12-06 14:11:24
@paul Reference for the deprecation please. And guess how numeric_limits implements max()? That's right, "return INT_MAX", at least on GCC 4.4.0.
anon
2009-12-06 14:14:29
@UncleBens: inline functions currently can't be reduced to constant expressions.
Georg Fritzsche
2009-12-06 15:04:19
Yes, I realized it has to be a function in the first place because `numeric_limits` has to be usable for non-integer types as well.
UncleBens
2009-12-06 15:32:49