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

They aren't.

What is the best way to implement these, as generically and type safe as possible (compiler extensions/builtins for mainstream compilers preferred).

As functions. I wouldn't use macros like #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y)), especially if you plan to deploy your code. Either write your own, use something like standard fmax or fmin, or fix the macro using GCC's typeof (you get typesafety bonus too) in a GCC statement expression:

 #define max(a,b) \
   ({ __typeof__ (a) _a = (a); \
       __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })

Everyone says "oh I know about double evaluation, it's no problem" and a few months down the road, you'll be debugging the silliest problems for hours on end.

Note the use of __typeof__ instead of typeof:

If you are writing a header file that must work when included in ISO C programs, write __typeof__ instead of typeof.

Answer from David Titarenco on Stack Overflow
Top answer
1 of 16
546

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

They aren't.

What is the best way to implement these, as generically and type safe as possible (compiler extensions/builtins for mainstream compilers preferred).

As functions. I wouldn't use macros like #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y)), especially if you plan to deploy your code. Either write your own, use something like standard fmax or fmin, or fix the macro using GCC's typeof (you get typesafety bonus too) in a GCC statement expression:

 #define max(a,b) \
   ({ __typeof__ (a) _a = (a); \
       __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })

Everyone says "oh I know about double evaluation, it's no problem" and a few months down the road, you'll be debugging the silliest problems for hours on end.

Note the use of __typeof__ instead of typeof:

If you are writing a header file that must work when included in ISO C programs, write __typeof__ instead of typeof.

2 of 16
129

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
🌐
W3Schools
w3schools.com › c › ref_math_fmin.php
C Math fmin() Function
C Examples C Real-Life Examples ... printf("%f", fmin(96, 2048)); Try it Yourself » · The fmin() function returns the number with the lowest value from a pair of numbers....
🌐
Qnx
qnx.com › developers › docs › 6.3.2 › neutrino › lib_ref › m › min.html
min()
#include <stdio.h> #include <stdlib.h> int main( void ) { int a; a = min( 1, 10 ); printf( "The value is: %d\n", a ); return EXIT_SUCCESS; }
🌐
Linux Hint
linuxhint.com › min-function-c
MIN() Macro in C Language – Linux Hint
Practical guide on how to use the macro MIN() to find the minimum value of two variables, how it works, and the expression and formula that this macro applies.
🌐
Particle
docs.particle.io › reference › device-os › api › math › min
min() - Math | Reference | Particle
NOTE: Perhaps counter-intuitively, max() is often used to constrain the lower end of a variable's range, while min() is used to constrain the upper end of the range. WARNING: Because of the way the min() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results · min(a++, 100); // avoid this - yields incorrect results a++; min(a, 100); // use this instead - keep other math outside the function ·
🌐
Reddit
reddit.com › r/c_language › add integer functions min and max to c language?
r/c_language on Reddit: Add integer functions min and max to C language?
July 30, 2023 -

The C programming language is missing library functions min and max for integer types. I am not aware of any argument to not provide them, given virtually every programming language providing them.

Relevance

For floats and doubles, fmin and fmax exists, but not for integer types. Other programming language provide them including C++ by std::min and std::max. Several C libraries provide them too, e.g., Linux, SuperLU, Cairo. Stackoverflow has a question with more then 400 upvotes, indicating that this is a real issue.

Add to C language?

Is it worthwhile to write a paper suggesting the addition of min and max? Or is there a reason that their addition has not already happened?

🌐
Cplusplus
cplusplus.com › reference › algorithm › min
std::min
Returns the smallest of a and b. If both are equivalent, a is returned. The versions for initializer lists (3) return the smallest of all the elements in the list. Returning the first of them if these are more than one. The function uses operator< (or comp, if provided) to compare the values.
Find elsewhere
🌐
Educative
educative.io › answers › how-to-use-min-function-in-cpp
How to use min() function in C++
The min() function in C++ accepts two values and returns the smaller one.
🌐
Math.js
mathjs.org › docs › reference › functions › min.html
Function min
In case of a multidimensional array, the minimum of the flattened array will be calculated. When dim is provided, the minimum over the selected dimension will be calculated. Parameter dim is zero-based. math.min(a, b, c, ...) math.min(A) math.min(A, dimension) Type | Description —- | ———– ·
🌐
Ticalc
tigcc.ticalc.org › doc › stdlib.html
stdlib.h
min is an inline function (implemented using GNU C smart macros) which returns the smaller of a and b. They may be any numeric values, either integer or floating point numbers, and they also may be pointers to the same base type. The result has the type of the argument which has greater range ...
🌐
GNU
gcc.gnu.org › onlinedocs › gcc-3.4.3 › gcc › Min-and-Max.html
Min and Max - Using the GNU Compiler Collection (GCC)
You might then use int min = MIN (i, j); to set min to the minimum value of variables i and j. However, side effects in X or Y may cause unintended behavior. For example, MIN (i++, j++) will fail, incrementing the smaller counter twice. The GNU C typeof extension allows you to write safe macros ...
🌐
Hacker News
news.ycombinator.com › item
Math.min(Math.max(num, min), max) | Hacker News
August 22, 2020 - I find the following easier to read : · Math.min(Math.max(num, lower_bound), upper_bound)
🌐
ScienceDirect
sciencedirect.com › topics › engineering › min-function
Min Function - an overview | ScienceDirect Topics
If A, B, C, etc. include a complex number, then the max function returns a complex number with the largest real part of any value, and i times the largest imaginary part of any value. For the min function, PTC Mathcad returns the smallest real part of any value, and i times the smallest imaginary part of any value.
🌐
Codecademy
codecademy.com › docs › c# › math functions › .min()
C# (C Sharp) | Math Functions | .Min() | Codecademy
March 2, 2023 - Math.Min() returns the lesser value from num1 and num2. The following example compares two integers i1 and i2 and writes the lesser integer to the console.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.math.min
Math.Min Method (System) | Microsoft Learn
Public Shared Function Min (val1 As UInteger, val2 As UInteger) As UInteger · val1 · UInt32 · The first of two 32-bit unsigned integers to compare. val2 · UInt32 · The second of two 32-bit unsigned integers to compare. UInt32 · Parameter val1 or val2, whichever is smaller. Attributes · CLSCompliantAttribute · Source: Math.cs ·
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 337349 › min-and-max-of-a-function-in-c
Min and max of a function in C++ | DaniWeb
For the concrete case a=5, b=7, c=1, d=20, integer y starts at 2 (since y=1 is invalid). The maximum is at (x,y)=(7,2) with f=8, and the minimum is at (5,20) with f=6/19. This matches the monotonicity of f(x,y)=(x+1)/(y-1): for y>1, f increases with x and decreases with y. Seems like part math ...
🌐
Edureka Community
edureka.co › home › community › categories › c++ › use of min and max functions in c
Use of min and max functions in C | Edureka Community
June 6, 2022 - Are std::min and std::max better than fmin and fmax in C++? Do they provide essentially the ... C standard (C99). Thank you very much in advance!
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › min
__min | Microsoft Learn
October 26, 2022 - // crt_minmax.c #include <stdlib.h> #include <stdio.h> int main( void ) { int a = 10; int b = 21; printf( "The larger of %d and %d is %d\n", a, b, __max( a, b ) ); printf( "The smaller of %d and %d is %d\n", a, b, __min( a, b ) ); } The larger of 10 and 21 is 21 The smaller of 10 and 21 is 10 · Math and floating-point support __max ·
🌐
Embarcadero
docwiki.embarcadero.com › Libraries › Sydney › en › System.Math.Min
System.Math.Min - RAD Studio API Documentation
Up to Parent: System.Math · Delphi ... Extended; C++ extern DELPHI_PACKAGE int __fastcall Min(const int A, const int B)/* overload */; Returns the lesser of two numeric values....