views:

602

answers:

2

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
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
exactly, thanks for the addition
Gregory Pakosz
+4  A: 
#include <climits>
#include <iostream>
using namespace std;

int main() {
  cout << INT_MAX << endl;
}
anon
I wouldn't call INT_MAX "a solution for C". It's old-school and deprecated in C++, though.
Paul Tomblin
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
The funny thing is that numeric_limits<int>::max implementation on msvc looks like this: return (INT_MAX);
Nikola Smiljanić
@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
@UncleBens: inline functions currently can't be reduced to constant expressions.
Georg Fritzsche
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
@gf: In C++1x they may, using `constexpr`.
dalle