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
🌐
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?

🌐
W3Schools
w3schools.com › c › ref_math_fmin.php
C Math fmin() Function
C Examples C Real-Life Examples ... fmin(96, 2048)); Try it Yourself » · The fmin() function returns the number with the lowest value from a pair of numbers....
🌐
Particle
docs.particle.io › reference › device-os › api › math › min
min() - Math | Reference | Particle
min(a++, 100); // avoid this - yields incorrect results a++; min(a, 100); // use this instead - keep other math outside the function
🌐
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 ...
Find elsewhere
🌐
GNU
gcc.gnu.org › onlinedocs › gcc-3.4.3 › gcc › Min-and-Max.html
Min and Max - Using the GNU Compiler Collection (GCC)
Using GNU C++ extensions, you can write int min = i <? j; instead. Since <? and >? are built into the compiler, they properly handle expressions with side-effects; int min = i++ <? j++; works correctly.
🌐
myCompiler
mycompiler.io › view › CQPGA2KSHE3
Write a C program to find maximum and minimum between two numbers using functions. (C) - myCompiler
September 15, 2022 - Copy link Download Share on Facebook Share on Twitter Share on Reddit Embed on website · #include<stdio.h> int max(int a,int b); int min(int a,int b); int main(){ int a=4,b=5; max(a,b); min(a,b); } int max(int a,int b){ if(a>b){ printf("Max=%d\n",a); } else{ printf("Max=%d\n",b); } } int min(int a,int b){ if(a<b){ printf("Min=%d\n",a); } else{ printf("Min=%d\n",b); } } Output ·
🌐
Arduino Forum
forum.arduino.cc › forum 2005-2010 (read only) › software › syntax & programs
Random max & min/max function C code - Syntax & Programs - Arduino Forum
November 11, 2009 - Hello, Would someone be able to point me to where I could find the C code used for the random max and random min/max functions. I would like to port them to an ATtiny project I am working on among other things. I've fo…
🌐
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.
🌐
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!

🌐
YouTube
youtube.com › user › yogawithadriene
Yoga With Adriene - YouTube
WELCOME to Yoga With Adriene! Our mission is to connect as many people as possible through high-quality free yoga videos. We welcome all levels, all bodies, all genders, all souls! If you're brand-new to yoga, check out my Yoga For Beginners and Foundations of Yoga series.
🌐
Shotarodabbs
shotarodabbs.com › zQrn
AntiBot Cloud: скрипт для защиты сайтов на php от плохих ботов.
February 15, 2026 - This process is automatic. Your browser will redirect to your requested content shortly · Please allow up to 1 seconds
🌐
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 ) ); }
🌐
MDCalc
mdcalc.com › calc › 3939 › ckd-epi-equations-glomerular-filtration-rate-gfr
CKD-EPI Equations for Glomerular Filtration Rate (GFR)
The CKD-EPI Creatinine Equation for Glomerular Filtration Rate (GFR) estimates GFR based on serum creatinine.
🌐
LWN.net
lwn.net › Articles › 983965
Maximal min() and max()
January 8, 2024 - One might not normally think of increased compilation time as one of them, though. It turns out that some changes to a couple of conceptually simple preprocessor macros — min() and max() — led to some truly pathological, but hidden, behavior where those macros were used.
🌐
Linux Man Pages
man7.org › linux › man-pages › man3 › max.3.html
MAX(3) - Linux manual page
MAX(3) Library Functions Manual MAX(3) MAX, MIN - maximum or minimum of two values · Standard C library (libc, -lc) #include <sys/param.h> MAX(a, b); MIN(a, b); These macros return the maximum or minimum of a and b. These macros return the value of one of their arguments, possibly converted ...
🌐
Cppreference
en.cppreference.com › w › cpp › algorithm › min.html
std::min - cppreference.com
#include <algorithm> #include <iostream> #include <string_view> int main() { std::cout << "smaller of 10 and 010 is " << std::min(10, 010) << '\n' << "smaller of 'd' and 'b' is '" << std::min('d', 'b') << "'\n" << "shortest of \"foo\", \"bar\", and \"hello\" is \"" << std::min({"foo", "bar", "hello"}, [](const std::string_view s1, const std::string_view s2) { return s1.size() < s2.size(); }) << "\"\n"; }
🌐
Science
science.org › doi › 10.1126 › sciadv.aea0753
Efficient AgInGaS-based QLEDs and full-color displays via uniform silver vacancy distribution | Science Advances
February 18, 2026 - In a typical synthesis (green cores), a reaction flask containing 0.08 mmol of In(ac)3, 0.24 mmol of HMy, 3.5 ml of ODE, and 15 ml of OAm was degassed at 110°C for 1 hour, backfilled with N2, and heated to 150°C. Then, 4.5 ml of Ag-S-Ga(OA)2 stock solution were swiftly injected into the flask to initiate nucleation and subsequent growth. The reaction temperature was maintained for 15 min and then gradually increased to 210°C at 4°C min−1 and held for 15 min to complete nucleation.
🌐
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
>> First off, absolute brute force isn't going to work in this case as the input is in floating point, and you can easily get a function that has maxima at non-integer values. ... Compute the minimal and the maximal value of function f(x,y) obtained on an integer point in a given rectangle [a, b] x [c, d]. The program should prompt the user to input numerical values of a, b, c and d, as floating point numbers, which are expected to be in a range from -100 thru 100.