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
🌐
OpenClassrooms
openclassrooms.com › accueil › forum › programmation › langage c › minimum en c
[Résolu] Minimum en C par YasminaDaliYoucef - page 1 - OpenClassrooms
Tu peux déjà essayer avec un nombre illimités de variable, ensuite tu remarqueras que ton code est simplifiable. Indice : lors de la simplification tu dois sans doute utiliser une boucle. ... Le principe est simple, tu as deux variables : tu demande deux nombres à l'utilisateur, tu les met dans les variables. Dans la première tu met le minimum des deux.
🌐
Developpez.net
developpez.net › forums › d2015195 › c-cpp › c › debuter › calcul-minimum-maximum-moyenne
Calcul minimum, maximum et moyenne - C
J'ai fait du python et disons que l'aspect structure de l'algorithme à mettre en place est très simple. Mais avec les subtilités du C (comme les conversions automatiques) il y a certainement choses qui m'échappe : Le problème c'est que j'obtiens 0 pour ma moyenne ^^' Et je doute fort que ma moyenne doit être théoriquement égale à 0
🌐
MacGeneration
forums.macg.co › développement › développement mac
fonction min/max en C/C++ | Les forums de MacGeneration
October 10, 2005 - Bonjour et bienvenue, Je ne sais pas si tu as réellement besoin d'une fonction min() et max(), car ce dont tu as besoin est de savoir si tu dépasse les heures aux taux horaires ou non... Par exemple si l'utilisateur entre 60 heures travaillées, bien il faut que je calcul une maximum de 40 heures * tauxHoraire, et la balance (en l'occurence 20 heures) * tauxDouble.
🌐
Ltam
ltam.lu › cours-c › solex62.htm
Solutions des exercices de programmation en C - Exercice 7.10 Maximum et minimum des valeurs d'un tableau
March 4, 2025 - #include <stdio.h> int main(void) { /* Déclarations */ int A[50]; /* tableau donné */ int N; /* dimension */ int I; /* indice courant */ int MIN; /* position du minimum */ int MAX; /* position du maximum */ /* Saisie des données */ printf("Dimension du tableau (max.50) : "); scanf("%d", &N ); for (I=0; I<N; I++) { printf("Elément %d : ", I); scanf("%d", &A[I]); } /* Affichage du tableau */ printf("Tableau donné :\n"); for (I=0; I<N; I++) printf("%d ", A[I]); printf("\n"); /* Recherche du maximum et du minimum */ MIN=0; MAX=0; for (I=0; I<N; I++) { if(A[I]>A[MAX]) MAX=I; if(A[I]<A[MIN]) MIN=I; } /* Edition du résultat */ printf("Position du minimum : %d\n", MIN); printf("Position du maximum : %d\n", MAX); printf("Valeur du minimum : %d\n", A[MIN]); printf("Valeur du maximum : %d\n", A[MAX]); return 0; }
🌐
OpenClassrooms
openclassrooms.com › accueil › forum › programmation › langage c › fonction min en c
FONCTION MIN EN C par LaureDeze - page 1 - OpenClassrooms
Et bien il faut la définir, c'est à dire, écrire le code de la fonction. Edgar ta mis un début de code. ... Elle n'est pas définie ta fonction MIN. (on ne met pas les nom de fonction en majuscules, les majuscules sont destinées aux macros).
🌐
Linux Hint
linuxhint.com › min-function-c
MIN() Macro in C Language – Linux Hint
The macro MIN() returns the minimum value between the “a” and “b” variables. The expression that is displayed by the macro MIN() is a true/false condition where a “<” relational operation is applied between the “a” and “b” variables. If “a” is less than “b”, “a” ...
Find elsewhere
🌐
GNU
gcc.gnu.org › onlinedocs › gcc-3.4.4 › 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 ...
🌐
Autotest
yard.onl › sitelycee › cours › c › Unminimumdecode.html
Un minimum de code
Code::blocks a donc généré le minimum de code en langage C dont on a besoin.
🌐
Exelib
exelib.net › langage-c › maximum-et-minimum-de-n-entiers.html
Maximum et minimum de N entiers - Langage C - Cours et Exercices corrigés
May 2, 2016 - //Programme : Maximum et minimum de N entiers //Auteur : IDMANSOUR //Copyright : Exelib.net #include <stdio.h> int main() { int i, n, a, nmax = 0, nmin = 0; printf("Entrer le nombre de valeurs: "); scanf("%d",&n); for(i=1; i<=n; i++) { printf("Entrez la valeur %d : ", i); scanf("%d",&a); //Initialisation du max et min if(i==1){ nmax = a; nmin = a; } if(a > nmax){ nmax = a; } if(a < nmin){ nmin = a; } } printf("Le maximum est: %d\n", nmax); printf("Le minimum est: %d\n", nmin); }
🌐
Cplusplus
cplusplus.com › reference › algorithm › min
Cplusplus
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.
🌐
Developpez.net
developpez.net › forums › d1284427 › c-cpp › c › debuter › fonction-minimum
fonction minimum ! - C
Es-tu conscient[e] que la dernière ligne ne sera appelée qu'une seulle fois, d'ailleurs puisqu'on parle de la dernière ligne tu écris "*mini=" alors qu'il n'y a pas de variable "mini" dans le code, quand au tableau "a" il est déclaré comme unidimensionnel, de toute façon même si il avait deux dimentions la fonction "mini" attend un tableau et pas une valeur dans un tableau, et puis n'as tu pas l'impression qu'il y a un peu trop de pointeurs? Bref, essaye d'écrire ton code plus clairement mais surtout étape par étape : Fais un code qui lit les valeurs entrées par l'utilisateur, puis qui les lit et les mets dans une matrice, puis...
🌐
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?

🌐
w3resource
w3resource.com › c-programming-exercises › inline_function › c-inline-function-exercise-3.php
C inline function - Compute the minimum of two integers
November 1, 2025 - In the above program, we define an inline function min() that takes two integers x and y as parameters and returns the minimum value between them. We use the ternary operator ? : to check which value is smaller and return it.
🌐
w3resource
w3resource.com › c-programming-exercises › array › c-array-exercise-9.php
C Program: Find the maximum and minimum element in an array - w3resource
September 27, 2025 - The next for loop then iterates over each element in arr1 and finds the maximum and minimum elements in the array by comparing it to every other element in the array using if statements.
🌐
Reddit
reddit.com › r/cprogramming › c code to find max and min values: unexpected results
r/cprogramming on Reddit: C code to find max and min values: unexpected results
January 12, 2025 -

Hi everyone,

I'm trying to find the maximum and minimum values in a C array, but I'm running into a problem. My code calculates the maximum value correctly, but the minimum value is always a very large negative number, even when all the values in the array are positive.

I've tried initializing the min variable to a large positive number, but it doesn't seem to help.

Here's my code:

#include <stdio.h>

int main(void)
{
    int i, sum = 0;
    int numbers [5];
    int min, max, average;
    
    printf("enter 5 numbers:\n");
    
    for (i = 0; i < 5; i++)
    {
        scanf("%d", &numbers[i]);
        sum += numbers[i];
    }
    
    max = numbers[i];
    min = numbers[i];
    
    for (i = 0; i < 5 ; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
        if (numbers[i] < min)
        {
            min = numbers[i];
        }
        
    }
    
    average = (double)sum/5;
    
    printf("Average is %d and sum is %d\n", average, sum);
    printf("Max number is %d and the min number is %d\n", max, min);
    
}

Can anyone help me figure out what's going wrong?

Thanks!

🌐
GNU
gnu.org › software › c-intro-and-ref › manual › html_node › Maximum-and-Minimum-Values.html
Maximum and Minimum Values (GNU C Language Manual)
There is no minimum limit symbol for types specified with unsigned because the minimum for them is universally zero. INT_MIN is not the negative of INT_MAX. In two’s-complement representation, the most negative number is 1 less than the negative of the most positive number.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › c-program-to-find-minimum-value-in-array
C Program to Find Minimum Value in Array - GeeksforGeeks
July 23, 2025 - In this article, we will learn how to find the minimum value in the array. The easiest and straightforward method is to iterate through each element of the array, comparing each value to an assumed minimum and updating it if the current value is less.