开发者

Why numeric_limits<int>::min() is differently defined?

To retrieve the smallest value i have to use numeric_limits<int>::min()

开发者_如何转开发

I suppose the smallest int is -2147483648, and tests on my machine showed this result. But some C++ references like Open Group Base Specifications and cplusplus.com define it with the value -2147483647.

I ask this question because in my implementation of the negaMax Framework (Game Tree Search) the value minimal integer * (-1) has to be well defined. Yes, with minimal int = (numeric_limits::min() + 2) i am on the safe side in any case, thus my question is more theoretically but i think nevertheless quite interesting.


If a value is represented as sign-and-magnitude instead of two's complement, the sign bit being one with all other bits as zero is equivalent to -0. In sign-and-magnitude the maximum positive integer and negative integer are the same magnitude. Two's complement is able to represent one more negative value because it doesn't have the same symmetry.


The value of numeric_limits<int>::min() is defined by implementation. That's why it could be different. You shouldn't stick to any concrete minimal value.


On cplusplus.com you forgot to read the qualifier

min. magnitude*

  • This is not necessarily the actual value of the constant in any particular compiler or system, it may be equal or greater in magnitude than this.


From the cplusplus.com link you posted (emphasis mine):

The following panel shows the different constants and their guaranteed minimal magnitudes (positive numbers may be greater in value, and negative numbers may be less in value). Any particular compiler implementation may define integral types with greater magnitudes than those shown here

Numeric limits are always system and compiler defined, try running with a 64bit compiler and system, you may see totally different numbers.


c++ uses two-s compliment for signed integers. Thus the smallest signed integer is defined by 100..00 (usually 32 bit).

Simply shifting 1<<(sizeof(int)*8-1) should give you the smallest signed integer.

Obviously for unsigned integers, the smallest is 0.

edit: you can read more here
edit2: apparently C++ doesn't necessarily use two-s compliment, my mistake

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜