MIN and MAX in C

后端 未结 14 1401
攒了一身酷
攒了一身酷 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:34

    I don't think that they are standardised macros. There are standardised functions for floating point already, fmax and fmin (and fmaxf for floats, and fmaxl for long doubles).

    You can implement them as macros as long as you are aware of the issues of side-effects/double-evaluation.

    #define MAX(a,b) ((a) > (b) ? a : b)
    #define MIN(a,b) ((a) < (b) ? a : b)
    

    In most cases, you can leave it to the compiler to determine what you're trying to do and optimise it as best it can. While this causes problems when used like MAX(i++, j++), I doubt there is ever much need in checking the maximum of incremented values in one go. Increment first, then check.

    0 讨论(0)
  • 2020-11-22 14:36

    It's also provided in the GNU libc (Linux) and FreeBSD versions of sys/param.h, and has the definition provided by dreamlax.


    On Debian:

    $ uname -sr
    Linux 2.6.11
    
    $ cat /etc/debian_version
    5.0.2
    
    $ egrep 'MIN\(|MAX\(' /usr/include/sys/param.h
    #define MIN(a,b) (((a)<(b))?(a):(b))
    #define MAX(a,b) (((a)>(b))?(a):(b))
    
    $ head -n 2 /usr/include/sys/param.h | grep GNU
    This file is part of the GNU C Library.
    

    On FreeBSD:

    $ uname -sr
    FreeBSD 5.5-STABLE
    
    $ egrep 'MIN\(|MAX\(' /usr/include/sys/param.h
    #define MIN(a,b) (((a)<(b))?(a):(b))
    #define MAX(a,b) (((a)>(b))?(a):(b))
    

    The source repositories are here:

    • GNU C Library
    • FreeBSD
    0 讨论(0)
提交回复
热议问题