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
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.
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: