Get the maximum value of a variable in C

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

    You can do it quite easily with a C11 type-generic expression:

    #define maxvalue(type) _Generic(type, int: INT_MAX, \
                                          unsigned int: UINT_MAX)
    

    It's not a function, but I think it does what you want. Here's a simple example program:

    #include 
    #include 
    
    #define maxvalue(type) _Generic(type, int: INT_MAX, \
                                          unsigned int: UINT_MAX)
    
    int main(void)
    {
        int i;
        unsigned int ui;
    
        printf("%u\n", maxvalue(i));
        printf("%u\n", maxvalue(ui));
    
        return 0;
    }
    

    And its output:

    $ clang -Wall -Werror -Wextra -pedantic -std=c11 example.c -o example
    $ ./example 
    2147483647
    4294967295
    

    My answers are larger than yours because my system has 32-bit integers. You appear to have a 16-bit machine.

提交回复
热议问题