C++ maximum non negative int

前端 未结 5 1561
既然无缘
既然无缘 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: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 
        const int OFFICIALMAXINT = numeric_limits::max();
    

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

    #include 
        const int OFFICIALMININT = numeric_limits::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.

提交回复
热议问题