Is there a C++ cross-platform library that provides me with a portable maximum integer number?
I want to declare:
const int MAX_NUM = /* call some library here */;
I use MSVC 2008 unmanaged.
In the C++ standard library header <limits>
, you will find:
std::numeric_limits<int>::max()
Which will tell you the maximum value that can be stored in a variable of type int
. numeric_limits
is a class template, and you can pass it any of the numeric types to get the maximum value that they can hold.
The numeric_limits
class template has a lot of other information about numeric types as well.
See limits.h
(C) or climits
(C++). In this case you would want the INT_MAX
constant.
I know it's an old question but maybe someone can use this solution:
int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)
So far we have -1 as result 'till size is a signed int.
size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.
As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.
As size is signed and negativ we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.
cout << size << endl; // Prints out size which is now set to maximum positive value.
We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.
I know the answer has been given but I just want to know from my old days, I used to do
int max = (unsigned int)-1
Will it give the same as
std::numeric_limits<int>::max()
?
On Hp UX with aCC compiler:
#include <iostream>
#include <limits>
using namespace std;
int main () {
if (sizeof(int)==sizeof(long)){
cout<<"sizeof int == sizeof long"<<endl;
} else {
cout<<"sizeof int != sizeof long"<<endl;
}
if (numeric_limits<int>::max()==numeric_limits<long>::max()){
cout<<"INT_MAX == lONG_MAX"<<endl;
} else {
cout<<"INT_MAX != LONG_MAX"<<endl;
}
cout << "Maximum value for int: " << numeric_limits<int>::max() << endl;
cout << "Maximum value for long: " << numeric_limits<long>::max() << endl;
return 0;
}
It prints:
sizeof int == sizeof long
INT_MAX != LONG_MAX
I checked both int and long types are 4bytes. manpage limits(5) says that INT_MAX and LONG_MAX are both 2147483647
http://nixdoc.net/man-pages/HP-UX/man5/limits.5.html
So, conclusion std::numeric_limits< type >:: is not portable.
精彩评论