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

前端 未结 10 618
爱一瞬间的悲伤
爱一瞬间的悲伤 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:33

    I guess you may want to check this link out:

    http://www.gnu.org/s/libc/manual/html_node/Infinity-and-NaN.html

    I did this and it works fine on gcc 4.4.1

    
    #include "math.h"
    
    int main(int argc, char**argv)
    { 
        int x = INFINITY; 
        return 0;
    }
    
    
    0 讨论(0)
  • 2020-12-01 18:34
    1. Firstly, include a header file named as math.h
    2. Now, equate INT_MAX to the integer whose value you want to set maximum. EXAMPLE:#include<math.h> //the header file which need to be included// int a=INT_MAX; //Suppose "a" be that integer whose value you want largest//
    0 讨论(0)
  • 2020-12-01 18:39

    There is a file called limits.h (at least on Linux there is), which holds this kind of definition e.g.

    /* Maximum value an `unsigned short int' can hold.  (Minimum is 0.)  */
    #  define USHRT_MAX 65535
    
    /* Minimum and maximum values a `signed int' can hold.  */
    #  define INT_MIN   (-INT_MAX - 1)
    #  define INT_MAX   2147483647
    
    /* Maximum value an `unsigned int' can hold.  (Minimum is 0.)  */
    #  define UINT_MAX  4294967295U
    
    0 讨论(0)
  • 2020-12-01 18:40

    I generally use the *_MAX macros found in limits.h INT_MAX for integers etc. These will always be correctly set for the variable type. Even the explicitly sized types such as uint32 will have corresponding entries in this header file.

    This has the virtue of being the largest possible value that a variable of that type can hold.

    For an unsigned integer as you asked for in your question, you would use UINT_MAX

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

    Normally this is done by 1.0/0.0, but you may get a compile warning on that. I am not aware of other portable ways of doing it in C89, but C99 has macro FP_INFINITE in math.h.

    EDIT: Apparently Sam didn't actually want infinity, but integer limits, which can be found in limits.h like others have stated.

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

    Based upon your comments, you want an unsigned int (although you say "unsigned integer", so maybe you want an integral value, not necessarily an unsigned int).

    In C, for unsigned integral type, the value -1, when converted to that type, is guaranteed to be largest value of that type:

    size_t size_max = -1;
    unsigned int uint_max = -1;
    unsigned long ulong_max = -1;
    

    assign the values SIZE_MAX, UINT_MAX and ULONG_MAX to the variables respectively. In general, you should include limits.h and use the appropriate macro, but it is nice to know the rule above. Also, SIZE_MAX is not in C89, so size_t size_max = -1; will work in C89 as well as C99.

    Note that the overflow behavior is guaranteed only for unsigned integral types.

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