How would you define a simple “min” method in obj-c

前端 未结 7 2234
感动是毒
感动是毒 2020-12-16 11:42

I want to define a min and max methods in a Utils class.

@interface Utils

int min(int a, int b);
int max(int a, int b);

@end

But I don\'t

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 12:03

    Here is a macro I created for multi-max and multi-min which allows more than just 2 inputs.

    float a = MMAX(1,2,9.33,2.5); //a = 9.33

    The internal mechanisms use long double and you'll just cast the output to whatever variable you're using. I'd prefer a solution using typeof but couldn't figure out how to do it on __VA_ARGS__ on a per argument basis, maybe someone more versed than me in C can figure it out and comment? Anyways, here's the macro definition:


    #define MMAX(...) ({\
    long double __inputs[(sizeof((long double[]){__VA_ARGS__})/sizeof(long double))] = {__VA_ARGS__};\
    long double __maxValue = __inputs[0];\
    for (int __i = 0; __i < (sizeof((long double[]){__VA_ARGS__})/sizeof(long double)); ++__i) {\
    long double __inputValue = __inputs[__i];\
    __maxValue = __maxValue>__inputValue?__maxValue:__inputValue;\
    }\
    __maxValue;\
    })
    
    #define MMIN(...) ({\
    long double __inputs[(sizeof((long double[]){__VA_ARGS__})/sizeof(long double))] = {__VA_ARGS__};\
    long double __minValue = __inputs[0];\
    for (int __i = 0; __i < (sizeof((long double[]){__VA_ARGS__})/sizeof(long double)); ++__i) {\
    long double __inputValue = __inputs[__i];\
    __minValue = __minValue<__inputValue?__minValue:__inputValue;\
    }\
    __minValue;\
    })
    

提交回复
热议问题