开发者

C++ maximum non negative int

Is the following going to work a开发者_如何转开发s expected on all platforms, sizes of int, etc? Or is there a more accepted way of doing it? (I made the following up.)

#define MAX_NON_NEGATIVE_INT ((int)(((unsigned int)-1) / 2))

I won't insult your intelligence by explaining what it's doing!

Edit: I should have mentioned that I cannot use any standard classes, because I'm running without the C runtime.


There is a standard way to this:

#include <limits>
#include <iostream>

cout << numeric_limits<unsigned int>::max();

Being standard, this is guaranteed to be portable across all platforms.


If you don't want to use defines (and you want a standard way of calculating the limits), then do this:

#include <limits>
std::numeric_limits<int>::min()

These are the ANSI standard defines in limits.h:

#define INT_MIN     (-2147483647 - 1) /* minimum (signed) int value */
#define INT_MAX       2147483647    /* maximum (signed) int value */
#define UINT_MAX      0xffffffff    /* maximum unsigned int value */

These are the defines from BaseTsd.h:

#define MAXUINT     ((UINT)~((UINT)0))
#define MAXINT      ((INT)(MAXUINT >> 1))
#define MININT      ((INT)~MAXINT)


#include <climits>


INT_MAX


You can have a look at the class numeric_limits, included in the standard library.

See here.


I would modify what you supplied just slightly, since you are coding C++ and not C.

const int MAXINT =(int)(((unsigned int)-1) >> 1), MININT = -MAXINT -1;

I prefer the right shift over the divide by 2, though they do the same thing, because bit shifting is more suggestive of the bit mangling used to generate MAXINT.

MAXINT yields the same thing as you'd get by using

#include <limits>
    const int OFFICIALMAXINT = numeric_limits<int>::max();

MININT yields the same thing as you'd get by using

#include <limits>
    const int OFFICIALMININT = numeric_limits<int>::min();

Hardcoding these values, as some above suggested, is a baaad idea.

I prefer the bit mangling, because I know it is always correct and I don't have to rely on remembering the library and the syntax of the call, but it does come down to a matter of preference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜