Get the maximum value of a variable in C

前端 未结 7 1775
感动是毒
感动是毒 2021-02-19 21:33

Is there a function in C that returns the maximum value of a variable like this (I will name the function \"maxvalue\" in example below)?

int a;
printf(\"%d\", m         


        
7条回答
  •  悲&欢浪女
    2021-02-19 21:39

    Such a function is not defined by the C standard library. You can try defining a macro that calculates it:

    #define MAX_VALUE(a) (((unsigned long long)1 << (sizeof(a) * CHAR_BIT)) - 1)
    

    When using it, be careful it is assigned to a type large enough. For example:

    #include 
    #include 
    #include 
    
    #define IS_TYPE_SIGNED(a) ((a-1) < 0)
    #define MAX_VALUE_UNSIGNED(a) (((unsigned long long)1 << \
            (sizeof(a) * CHAR_BIT)) - 1)
    #define MAX_VALUE_SIGNED(a) (MAX_VALUE_UNSIGNED(a) >> 1)
    #define MAX_VALUE(a) (IS_TYPE_SIGNED(a) ? \
            MAX_VALUE_SIGNED(a) : MAX_VALUE_UNSIGNED(a))
    
    int main(void)
    {
        unsigned int i = 0;
        signed int j = 0;
    
        printf("%llu\n", MAX_VALUE(i));
        printf("%llu\n", MAX_VALUE(j));
        return EXIT_SUCCESS;
    }
    

    This prints out:

    4294967295
    2147483647
    

提交回复
热议问题