Get the maximum value of a variable in C

前端 未结 7 1774
感动是毒
感动是毒 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:45

    Here are macros from my library that work for types, rather than variables:

    /* min and max integer values.  T is a signed or unsigned integer type. */
    
    /* Returns 1 if T is signed, else 0. */
    #define INTTYPE_SIGNED(T) ((T)-1 < (T)0)
    
    /*
     * Returns (T)(maximum value of a T).
     *
     * Pains are taken (perhaps unnecessarily) to avoid integer overflow
     * with signed types.
     */
    #define INTTYPE_MAX(T)                      \
        (((T)1 << (CHAR_BIT*sizeof(T)-INTTYPE_SIGNED(T)-1)) - 1 +   \
         ((T)1 << (CHAR_BIT*sizeof(T)-INTTYPE_SIGNED(T)-1)))
    
    /*
     * Returns (T)(minimum value of a T).
    
     * Pains are taken (perhaps unnecessarily) to avoid integer overflow
     * with signed types.
     * assert: twos complement architecture
     */
    #define INTTYPE_MIN(T) ((T)(-INTTYPE_MAX(T)-1))
    

    Edit: Adapting these to the question:

    /* min and max integer values.  V is a signed or unsigned integer value. */
    
    /* Returns 1 if V has signed type, else 0. */
    #define INT_VALUE_SIGNED(V) ((V)-(V)-1 < 0)
    
    /*
     * Returns maximum value for V's type.
     *
     * Pains are taken (perhaps unnecessarily) to avoid integer overflow
     * with signed types.
     */
    #define INT_VALUE_MAX(V)                        \
        (((V)-(V)+1 << (CHAR_BIT*sizeof(V)-INT_VALUE_SIGNED(V)-1)) - 1 +    \
         ((V)-(V)+1 << (CHAR_BIT*sizeof(V)-INT_VALUE_SIGNED(V)-1)))
    
    /*
     * Returns minimum value for V's type.
    
     * Pains are taken (perhaps unnecessarily) to avoid integer overflow
     * with signed types.
     * assert: twos complement architecture
     */
    #define INT_VALUE_MIN(V) (-INT_VALUE_MAX(V)-1)
    

    Afterthought: These invoke UB if V is a variable, or an expression containing variables, that have not been assigned a value ... which is the case in the question as asked. They are likely to work on many implementations, but the C standard doesn't guarantee it, and they will certainly fail on an implementation that initializes uninitialized variables with trap values.

提交回复
热议问题