Any C library which defines a macro named max in its standard headers is broken beyond imagination. Fortunately, an easy workaround if you need to support such platforms is to #undef max (and any other problematic macros it defines) after including the system headers and before any of your own headers/code.

Note that everyone else is saying to wrap your definition in #ifndef max ... #endif. This is not a good idea. Defining max in a system header is an indication that the implementor was incompetent, and it's possible that certain versions of the environment have incorrect macros (for example, ones which do not properly protect arguments with parentheses, but I've even seen a max macro that was incorrectly performing min instead of max at least once in my life!). Just use #undef and be safe.

As for why it's so broken for stdlib.h to define max, the C standard is very specific about what names are reserved for the application and what names are reserved for standard functions and/or internal use by the implementation. There are very good reasons for this. Defining macro names in system headers that could clash with variable/function names used in the application program is dangerous. In the best case it leads to compile-time errors with an obvious cause, but in other cases it can cause very strange behavior that's hard to debug. In any case it makes it very difficult to write portable code because you never know what names will already be taken by the library.

Answer from R.. GitHub STOP HELPING ICE on Stack Overflow
Top answer
1 of 5
43

Any C library which defines a macro named max in its standard headers is broken beyond imagination. Fortunately, an easy workaround if you need to support such platforms is to #undef max (and any other problematic macros it defines) after including the system headers and before any of your own headers/code.

Note that everyone else is saying to wrap your definition in #ifndef max ... #endif. This is not a good idea. Defining max in a system header is an indication that the implementor was incompetent, and it's possible that certain versions of the environment have incorrect macros (for example, ones which do not properly protect arguments with parentheses, but I've even seen a max macro that was incorrectly performing min instead of max at least once in my life!). Just use #undef and be safe.

As for why it's so broken for stdlib.h to define max, the C standard is very specific about what names are reserved for the application and what names are reserved for standard functions and/or internal use by the implementation. There are very good reasons for this. Defining macro names in system headers that could clash with variable/function names used in the application program is dangerous. In the best case it leads to compile-time errors with an obvious cause, but in other cases it can cause very strange behavior that's hard to debug. In any case it makes it very difficult to write portable code because you never know what names will already be taken by the library.

2 of 5
12

So answering your main question:

Is max(a,b) defined in stdlib.h or not?

No it isn't, it's defined in windef.h around line 187:

#ifndef NOMINMAX

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

#ifndef min
#define min(a,b)            (((a) < (b)) ? (a) : (b))
#endif

#endif  /* NOMINMAX */
🌐
Reddit
reddit.com › r/c_programming › is max() predefined or not ?
r/C_Programming on Reddit: Is max() predefined or not ?
April 23, 2023 -

Sorry for the newbie question, I'm looking for a way to find the maximum between two values in C and I stumbled upon this, which make it sound like max() is a macro defined in stdlib.h, however when I look up the file I can't find it, and when I try to compile the example I get an 'implicit declaration' warning then an 'undefined reference' at execution.

That stackoverflow discussion seems to go that way and suggests that one uses fmax from the math library, or write the max() themselves.

I don't know if I'm just bad at reading documentation or if there's actually something special about that I should know about. Either way if someone can help me figuring this out, i'd be grateful.

(PS : it's for a school project where I won't have any issues with double evaluation so a dirty solution will do)

Discussions

MIN and MAX in C - Stack Overflow
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? (Compiler extensions/builtins for mainstream compilers preferred.) More on stackoverflow.com
🌐 stackoverflow.com
min/max in stdlib.h?!
But consider the following strictly ... 1); return 0; } I don't have lcc-win, but my compiler (when I replace the "#include " with your definition of max) chokes on the function declaration; I presume lcc-win does as well.... More on thecodingforums.com
🌐 thecodingforums.com
40
December 18, 2007
Is max() predefined or not ?
It's not a standard library function or macro. Some implementations may provide it. Presumably QNX does. But I bet you're not using QNX... so you probably shouldn't look at that documentation. More on reddit.com
🌐 r/C_Programming
12
7
April 23, 2023
How much of the stdlib is useless when working on embedded systems?
It dawned on my that there is no operating system and as such all the data structures like std::vector, std::Youunordered_map etc are rendered useless You don't need an OS to use allocation. Usually, these embedded targets define a region of memory as a heap, and the libc provides a malloc implementation, on top of which you can have new. Just try it More on reddit.com
🌐 r/cpp
89
70
November 14, 2024
🌐
Ticalc
tigcc.ticalc.org › doc › stdlib.html
stdlib.h
RAND_MAX is a constant (here with value 32767) which is usually defined in stdlib.h. Its meaning is "the largest number returned by rand". Describes an exit function passed to atexit.
🌐
Cppreference
en.cppreference.com › w › cpp › algorithm › max.html
std::max - cppreference.com
December 5, 2024 - int n = -1; const int& r = std::max(n + 2, n * 2); // r is dangling ... #include <algorithm> #include <iomanip> #include <iostream> #include <string_view> int main() { auto longest = [](const std::string_view s1, const std::string_view s2) { return s1.size() < s2.size(); }; std::cout << "Larger ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › max
__max | Microsoft Learn
October 26, 2022 - The __max macro compares two values and returns the value of the larger one. The arguments can be of any numeric data type, signed or unsigned. Both arguments and the return value must be of the same data type.
🌐
Launchpad
answers.launchpad.net › ubuntu › +source › gnome-terminal › +question › 82506
Question #82506 “max() or min() functions in stdlib.h” : Questions : gnome-terminal package : Ubuntu
June 6, 2022 - There is fmax/fmin, but since max and min are so trivial to write ... Here are a couple implementations: #define ( MAX( a, b ) ( ( a > b) ? a : b ) ) inline int max ( int a, int b ) { return a > b ?
🌐
Embarcadero
docwiki.embarcadero.com › RADStudio › Sydney › en › Max
max (C++) - RAD Studio
stdlib.h · Category · C++ Prototyped Routines · Prototype · (type) max(a, b); template <class T> T max( T t1, T t2 ); // C++ only · Description · Returns the larger of two values. The C macro and the C++ template function compare two values and return the larger of the two.
🌐
Qnx
qnx.com › developers › docs › 6.5.0SP1 › neutrino › lib_ref › m › max.html
max()
The max() function returns the greater of two values. #include <stdio.h> #include <stdlib.h> int main( void ) { int a; a = max( 1, 10 ); printf( "The value is: %d\n", a ); return EXIT_SUCCESS; }
Find elsewhere
🌐
Cplusplus
cplusplus.com › reference › algorithm › max
std::max
Returns the largest of a and b. If both are equivalent, a is returned. The versions for initializer lists (3) return the largest 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.
🌐
AlphaCodingSkills
alphacodingskills.com › c › notes › c-math-fmax.php
C - fmax() Function - AlphaCodingSkills
December 17, 2023 - If one of the arguments is NaN, then the other argument is returned. double fmax (double x, double y); float fmaxf (float x, float y); long double fmaxl (long double x, long double y); Returns the numerically maximum value. In the example below, fmax() function is used to find out the maximum ...
🌐
Narkive
openwatcom.users.c-cpp.narkive.com › QvDdj60Z › max-min-macros-are-not-been-declared-in-stdlib-h-for-c
max/min macros are not been declared in stdlib.h for C++
January 11, 2025 - Such support could be arranged in this case by introducing a global function max() that is only visible when stdlib.h is compiled by the C++ compiler. However that would conflict with similar definitions in third party headers (for example, older C++ code) and the #if !defined(max) #endif trick ...
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
🌐
The Coding Forums
thecodingforums.com › archive › archive › c programming
min/max in stdlib.h?! | C Programming | Coding Forums
December 18, 2007 - But consider the following strictly conforming program: #include <stdlib.h> int max(int a, int b) { return a > b ? a : b; } int main(void) { int n = max(0, 1); return 0; } I don't have lcc-win, but my compiler (when I replace the "#include ...
🌐
Linux Man Pages
man7.org › linux › man-pages › man3 › max.3.html
MAX(3) - Linux manual page
#include <stdio.h> #include <stdlib.h> #include <sys/param.h> int main(int argc, char *argv[]) { int a, b, x; if (argc != 3) { fprintf(stderr, "Usage: %s <num> <num>\n", argv[0]); exit(EXIT_FAILURE); } a = atoi(argv[1]); b = atoi(argv[2]); x = MAX(a, b); printf("MAX(%d, %d) is %d\n", a, b, x); exit(EXIT_SUCCESS); } fmax(3), fmin(3) This page is part of the man-pages (Linux kernel and C library user-space interface documentation) project.
🌐
Digitalmars
digitalmars.com › rtl › stdlib.html
stdlib.h - Digital Mars
January 5, 2008 - ... The larger value in arguments a or b. ... /* Example of __max */ #include <stdlib.h> #include <stdio.h> void main() { int x = 5, y = 6, z, w; z = __max(x, y); w = __min(x, y); printf("The max should be 6 and is %d\n", z); printf("The min should be 5 and is %d\n", w); }
🌐
Mikroe
download.mikroe.com › documents › compilers › mikroc › pic32 › help › ansi_stdlib_library.htm
ANSI C Stdlib Library
November 11, 2009 - The functions have been mostly implemented according to the ANSI C standard, but certain functions have been modified in order to facilitate PIC32 programming.
🌐
Bytes
bytes.com › topic › c › answers › 755688-min-max-stdlib-h
min/max in stdlib.h?! - C / C++ - Bytes.com
November 24, 2024 - What to do: • Humans: Wait a few minutes and try again • Bots: Implement proper crawl delays and respect our limits • Developers: Check your automation scripts for excessive requests
🌐
C For Dummies
c-for-dummies.com › blog
Min and Max | C For Dummies Blog
September 1, 2013 - Such examples are missing in my C programming books, but that doesn’t mean you miss out on the fun. Below you see sample code that carries out the basic operations for the exercise: An array is created and filled with random values. Your job is to craft the array_max() and array_min() functions, stubbed out in the code. #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 20 int array_max(int *a,int s); int array_min(int *a,int s); int main() { int array[SIZE]; int x; /* Fill the array with random values */ srand((unsigned)time(NULL)); /* seed randomizer */ for(x=0;x<SIZE;x+
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › stdlib_h.htm
C Library - <stdlib.h>
The stdlib.h header defines four variable types, several macros, and various functions for performing general functions. Following are the variable types defined in the header stdlib.h − Following are the macros defined in the header stdlib.h −
🌐
Quora
quora.com › What-is-the-purpose-of-the-max-function-in-C-programming
What is the purpose of the 'max' function in C programming? - Quora
December 5, 2024 - Learning C (programming l... ... UG in Bachelor of Engineering Degrees & Biomedical Engineering, Karpagam Academy of Higher Education (Graduated 2024) · 2y · The "max" function in C compares two integers and returns the larger value.