C++ maximum non negative int

前端 未结 5 1443
既然无缘
既然无缘 2021-01-28 12:24

Is the following going to work as expected on all platforms, sizes of int, etc? Or is there a more accepted way of doing it? (I made the following up.)

#define M         


        
相关标签:
5条回答
  • 2021-01-28 12:31

    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.

    0 讨论(0)
  • 2021-01-28 12:37

    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)
    
    0 讨论(0)
  • 2021-01-28 12:52

    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 讨论(0)
  • 2021-01-28 12:56

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

    See here.

    0 讨论(0)
  • 2021-01-28 12:57
    #include <climits>
    
    
    INT_MAX
    
    0 讨论(0)
提交回复
热议问题