MIN and MAX in C

后端 未结 14 1413
攒了一身酷
攒了一身酷 2020-11-22 13:32

Where are MIN and MAX defined in C, if at all?

What is the best way to implement these, as generically and type safely as possible? (Compil

14条回答
  •  死守一世寂寞
    2020-11-22 14:21

    This is a late answer, due to a fairly recent development. Since the OP accepted the answer that relies on a non-portable GCC (and clang) extension typeof - or __typeof__ for 'clean' ISO C - there's a better solution available as of gcc-4.9.

    #define max(x,y) ( \
        { __auto_type __x = (x); __auto_type __y = (y); \
          __x > __y ? __x : __y; })
    

    The obvious benefit of this extension is that each macro argument is only expanded once, unlike the __typeof__ solution.

    __auto_type is a limited form of C++11's auto. It cannot (or should not?) be used in C++ code, though there's no good reason not to use the superior type inference capabilities of auto when using C++11.

    That said, I assume there are no issues using this syntax when the macro is included in an extern "C" { ... } scope; e.g., from a C header. AFAIK, this extension has not found its way info clang

提交回复
热议问题