How would you set a variable to the largest number possible in C?

前端 未结 10 619
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 17:53

How would you set a variable to equal infinity (or any guaranteed largest number value) in C?

相关标签:
10条回答
  • 2020-12-01 18:44

    By far the simplest method to get the largest value for an unsigned integer type is to cast (-1) to that type. The standard (§6.2.5/9) requires that unsigned math be carried out modulo a number one greater than the largest value that can be represented, so for any unsigned type T, the expression ((T)-1) will necessarily be the largest value possible in that type.

    0 讨论(0)
  • 2020-12-01 18:45
    #include <limits.h>
    int x = INT_MAX;
    

    EDIT: answered before the questioner clarified, I was just guessing what type they wanted.

    0 讨论(0)
  • 2020-12-01 18:47

    Since there's a C++ tag on this question, I'll suggest numeric_limits:

    #include <limits>
    
    unsigned x = std::numeric_limits<unsigned>::max();
    
    0 讨论(0)
  • 2020-12-01 18:54

    Another portable way to get maximum value of integer:

    Unsigned integer

    unsigned int uMax = (unsigned int)~0;
    

    Signed integer

    signed int iMax = (unsigned int)~0 >> 1;
    

    Explanation

    • ~0 -> setting all bits to one
    • >> 1 -> erasing sign bit, by shifting all bits to the right by one position
    • (unsigned int) typecasting to unsigned int after bits inversion instead of using ~0U, because C doesn't have a suffix for short,char literals (everything smaller than int in general)

    So for biggest possible char value - just change in formula typecasting to unsigned char and etc.

    Bonus - minimum value of signed int

    Simply just invert all bits once more in max signed int expression:

    signed int iMin = ~((unsigned int)~0 >> 1);
    

    That sets first sign bit to one and the rest bits - to zero

    0 讨论(0)
提交回复
热议问题