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
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "c howtos" › "min and max function in c"
MIN and MAX Function in C | Delft Stack
October 12, 2023 - Inside the MAX() and MIN() function, we stored the first element of the array in a variable, and then we compared it with all the other elements of the array using a loop that will stop when the integer i becomes equal to the length of the array which means the loop has reached the end of the array.
Top answer
1 of 16
549

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
131

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
Discussions

Using C to Find Min and Max value using Function - Stack Overflow
So, now the function max() returned ... and we store it in our maxi variable like maxi = max(maxi, x). Now, maxi is not being changed it the function max so there is no issue in using it like that. Hope that helps. 2020-10-12T06:38:08.047Z+00:00 ... The program checks the last number because you are calling the min and max function ... More on stackoverflow.com
🌐 stackoverflow.com
Add integer functions min and max to C language?
C is not a batteries included language. These are extremely easy to implement using a function or macro. Literally one-liners that are impossible to screw up. The reason why fmin et al exist is that there are eccentricities to floating point types and it's not a simple comparison. For example, is 7 > NAN? More on reddit.com
🌐 r/c_language
4
2
July 30, 2023
C code to find max and min values: unexpected results
After the first loop, the value of i is 5, and the following is undefined, you are reading past the last element of the array numbers: max = numbers[i]; min = numbers[i]; To understand why, note that the loop for (i = 0; i < 5; i++) { /* loop body */ } is exactly equivalent to i = 0; while (i < 5) { /* loop body */ i++; } The while loop stops when the test is no longer true, that is, at i=5. Therefore, just after the loop, i=5. Then, you are reading a number in memory, just after the array. It's invalid, but the program simply reads the value there. It happens to be a large negative number. If you initialize min and max at the beginning of the function, but leave those two lines, the initial value is just overwritten with this invalid value. The simplest to fix this would be to initialize with numbers[0]. And the next for loop may start at i=1, since the 0 case is already taken into account. You have another problem: since average is an int, the exact average will be truncated. You may declare average as a double instead, and change the printf format specifier accordingly. More on reddit.com
🌐 r/cprogramming
13
7
January 12, 2025
c++ - What are the MAX and MIN in C? #define function - Stack Overflow
I am a student and my teacher gave me and exercise already solved for studying, in his exercise I see this line: #define MIN(a,b) ((a) More on stackoverflow.com
🌐 stackoverflow.com
🌐
Codeforwin
codeforwin.org › home › c program to find maximum and minimum using functions
C program to find maximum and minimum using functions - Codeforwin
July 20, 2025 - After combining the above three ... from user */ printf("Enter any two numbers: "); scanf("%d%d", &num1, &num2); maximum = max(num1, num2); // Call maximum function minimum = min(num1, num2); // Call minimum function ...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › c-program-to-find-the-maximum-and-minimum-element-of-the-array
C Program to Find the Maximum and Minimum Element in the Array - GeeksforGeeks
July 12, 2025 - The simplest method to find the maximum and minimum element of the array is iterates through the array and compare each element with the assumed minimum and maximum and update them if the current element is smaller or larger respectively.
🌐
Linux Hint
linuxhint.com › min-and-max-in-c
Min and Max in C – Linux Hint
However, if a user doesn’t want to go into a detailed process, they can go with using the built-in functions in C called ‘fmin()’ and ‘fmax()’. These functions fetch the min or max element from a specific subset or range of the array. To use the ‘fmin’ and ‘fmax’ functions, ...
Top answer
1 of 5
1

Okay, the thing is that you are not updating the data_input after every successive number is inputted. What you are doing is, comparing the last number to 0 or 100, which is logically incorrect. How about you take the first number as input, then after every successive input, compare it with the min and max value. Here is the sample code.

#include <stdio.h>
float max(float num1, float num2){
    if(num1 > num2){
        return num1;
    }
    return num2;
}

float min(float num1, float num2){
    if(num1 < num2){
        return num1;
    }
    return num2;
}

int main(){
    int times, interval;
    float mini, maxi, data_Input;

    printf("How many number would you like to type in ? : ");
    scanf("%d\n",&times);

    printf("Type in the number: ");
    scanf("%f", &data_Input);
    
    // the first number will be minimum and maximum
    mini = data_Input;
    maxi = data_Input;

    for(interval=2; interval<=times; interval++){
        printf("\nType in the number: ");
        scanf("%f",&data_Input);
        // make it a composite if condition
        while(data_Input<0 || data_Input>100){
            printf("Invalid Input! Please re-enter the number:");
            scanf("%f",&data_Input);
        }
        maxi= max(maxi, data_Input);
        mini= min(mini, data_Input);
    
    }
    

    printf("The Lowest Number is %.2f\n", mini);
    printf("The Highest Number is %.2f\n", maxi);
    return 0;
}
2 of 5
0

The program checks the last number because you are calling the min and max function out of the for bracelets so instead you can call them inside the for bracelets like:

for(interval=2; interval<=times; interval++){
        printf("\nType in the number: ");
        scanf("%f",&data_Input);
        while(data_Input<0){
            printf("Invalid Input! Please re-enter the number:");
            scanf("%f",&data_Input);
        }
        while(data_Input>100){
            printf("Invalid Input! Please re-enter the number:");
            scanf("%f",&data_Input);
        }
        maxi= max(data_Input);
        mini= min(data_Input);
    }

and instead of rewriting the same code you can just ask for the numbers inside the for loop and to initialize your interval to 1 so your main will look like:

int main(){
    int times, interval;
    float mini, maxi, data_Input;

    printf("How many number would you like to type in ? : ");
    scanf("%d\n",&times);

    for(interval=1; interval<=times; interval++){
        printf("\nType in the number: ");
        scanf("%f",&data_Input);
        while(data_Input<0){
            printf("Invalid Input! Please re-enter the number:");
            scanf("%f",&data_Input);
        }
        while(data_Input>100){
            printf("Invalid Input! Please re-enter the number:");
            scanf("%f",&data_Input);
        }
        maxi= max(data_Input);
        mini= min(data_Input);
    }

    printf("The Lowest Number is %.2f\n", mini);
    printf("The Highest Number is %.2f\n", maxi);
    return 0;
}
🌐
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?

Find elsewhere
🌐
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!
🌐
C For Dummies
c-for-dummies.com › blog
Min and Max | C For Dummies Blog
September 1, 2013 - array_chop() This function (actually a family of functions) slices, dices, splits and spits up an array in various ways. array_max() This function returns the highest (maximum) value of all the values stored in the array. array_min() This function returns the lowest (minimum) value stored in ...
🌐
GNU
gcc.gnu.org › onlinedocs › gcc-3.4.2 › gcc › Min-and-Max.html
Min and Max - Using the GNU Compiler Collection (GCC)
For example, MIN (i++, j++) will fail, incrementing the smaller counter twice. The GNU C typeof extension allows you to write safe macros that avoid this kind of problem (see Typeof). However, writing MIN and MAX as macros also forces you to use function-call notation for a fundamental arithmetic operation.
🌐
w3resource
w3resource.com › c-programming-exercises › variadic › c-variadic-exercise-3.php
C Variadic function - Maximum and minimum of a variable number of integers
November 1, 2025 - In the above code, the max() and min() functions take a variable number of arguments using the ...
🌐
GitHub
github.com › willemt › minmax
GitHub - willemt/minmax: min and max functions for C · GitHub
min and max functions for C. Contribute to willemt/minmax development by creating an account on GitHub.
Starred by 5 users
Forked by 2 users
Languages: C++
🌐
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!

🌐
Quora
quora.com › In-C-the-max-and-min-function-only-allow-two-numbers-so-how-do-you-find-the-max-of-four
In C++, the max() and min() function only allow two numbers, so how do you find the max of four? - Quora
Answer (1 of 5): Why not write your own recursive max function? The function could take an arbitrarily long list of integers as its input. If the length of the list is two, then it would return the C++ [code ]max[/code] of the two elements in the list. Otherwise, return the C++ [code ]max[/code] ...
🌐
W3Schools
w3schools.com › c › ref_math_fmax.php
C Math fmax() Function
The fmax() function is defined in the <math.h> header file. Tip: Use the fmin() function to return the number with the lowest value. ... Coding fundamentals as bite-sized lessons and challenges.
🌐
Scribd
scribd.com › document › 455070615 › FUNCTIONS
C Program for Max and Min Functions | PDF | Pointer (Computer Programming) | Matrix (Mathematics)
The document contains C program code snippets demonstrating the use of functions and pointers to perform common tasks like finding maximum/minimum, checking if a number is prime, calculating factorials, Fibonacci series, summing array elements, and more. Each code snippet is preceded by a brief description and includes main() function, other required functions, sample input/output.
🌐
Linux Hint
linuxhint.com › min-function-c
MIN() Macro in C Language – Linux Hint
Also, these functions process the non-numeric values (NaN). In this Linuxhint article, we explained everything you need to know to use the macro MIN() to find the minimum value between two variables. We looked at the syntax and definition of this macro, as well as the formula that applies a true/false condition for a “less than” operation ( < ) between the two input variables.
🌐
Launchpad
answers.launchpad.net › ubuntu › +source › gnome-terminal › +question › 82506
Question #82506 “max() or min() functions in stdlib.h” : Questions : gnome-terminal package : Ubuntu
As far as I'm aware, there is no max or min function in the C or GNU standard libraries. There is fmax/fmin, but since max and min are so trivial to write ...