Get the maximum value of a variable in C

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

    You cannot create a function that does this, but you can create some macros that do this.

    If you have C11 you can use _Generic:

    #define maxvalue(x) \
      _Generic(x, \
          char: 127, short: 32767, int: INT_MAX, \
          unsigned char: 255, unsigned short: 65535, unsigned int: UINT_MAX)
    

    If you need C89, you can do it if you can differentiate between signed/unsigned:

    #define maxvalue_unsigned(x) ((1<<(8*sizeof(x)))-1)
    #define maxvalue_signed(x) ((1<<((8*sizeof(x)-1)))-1)
    

    If you're willing to require the typename (or use the GCC-specific typename) you could use strings:

    #define maxvalue_type(x) maxvalue_helper(#x "----------")
    unsigned long long maxvalue_helper(const char *s) {
      switch(*s){
      char 'c': /* char */ return 127;
      char 's': /* short */ return 32767;
      char 'i': /* int */ return INT_MAX;
      /* ... */
      case 'u': /* unsigned */
        switch(9[s]) {
        case 'c': /* unsigned char */ return 255;
        char 's': /* unsigned short */ return 65535;
        char 'i': /* unsigned int */ return UINT_MAX;
        /* ... */
    

提交回复
热议问题