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)

🌐
Ticalc
tigcc.ticalc.org › doc › stdlib.html
stdlib.h
max is an inline function (implemented using GNU C smart macros) which returns the greater 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 ...
🌐
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; }
🌐
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 ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › max
__max | Microsoft Learn
... A preprocessor macro that returns the larger of two values. ... 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.
🌐
Cppreference
en.cppreference.com › w › cpp › algorithm › max.html
std::max - cppreference.com
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 of 69 and 96 is " << std::max(69, 96) << "\n" "Larger of 'q' and 'p' is '" << std::max('q', 'p') << "'\n" "Largest of 010, 10, 0X10, and 0B10 is " << std::max({010, 10, 0X10, 0B10}) << '\n' << R"(Longest of "long", "short", and "int" is )" << std::quoted(std::max({"long", "short", "int"}, longest)) << '\n'; }
🌐
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.
Find elsewhere
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
🌐
Mikroe
download.mikroe.com › documents › compilers › mikroc › pic32 › help › ansi_stdlib_library.htm
ANSI C Stdlib Library
The mikroC PRO for PIC32 provides a set of standard ANSI C library functions of general utility.
🌐
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++
So there isn't really a great resolution. Considering that Standard C++ *does* provide a max function in namespace std, I'm inclined to say that people should just use that. Post by Evgeny Kotsuba Moreover, Max/min macros are placed inside WATCOM\h\cstdlib that is included from stdlib.h....
🌐
The Coding Forums
thecodingforums.com › archive › archive › c programming
min/max in stdlib.h?! | C Programming | Coding Forums
January 24, 2008 - Click to expand... No, they don't. If they are nevertheless placed there by the implementation, check that you are invoking the implementation in conforming mode. If so, then you have uncovered a bug in the implementation. ... Are the macros min() and max() part of stdlib.h or not?
🌐
Cplusplus
cplusplus.com › reference › algorithm › max
std::max - algorithm
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.
🌐
C For Dummies
c-for-dummies.com › blog
Min and Max | C For Dummies Blog
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++) array[x] = rand() % 100 + 1; /* Display the array */ puts("The Array:"); for(x=0;x<SIZE;x++) printf("= ",array[x]); putchar('\n'); printf("Highest value: %d\n", array_max(array,SIZE)); printf("Lowest value: %d\n", array_min(array,SIZE)); return(0); } int array_max(int *a,int s) { } int array_min(int *a,int s) { }
🌐
AlphaCodingSkills
alphacodingskills.com › c › notes › c-math-fmax.php
C - fmax() Function - AlphaCodingSkills
C Library - <stdlib.h> C Library - <string.h> C Library - <time.h> C Library - <wchar.h> C Library - <wctype.h> The C <math.h> fmax() function returns maximum number between the two arguments. If one of the arguments is NaN, then the other argument is returned.
🌐
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.
🌐
stdlib
stdlib.io › docs › api › latest › @stdlib › math › base › special › max
max | math.base | stdlib
var minstd = require( ... 'max(%d,%d) = %d', x, y, v ); } #include "stdlib/math/base/special/max.h" Returns the maximum value. double out = stdlib_base_max( 4.2, 3.14 ); // returns 4.2 out = stdlib_base_max( ...
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › stdlib_h.htm
C Library - <stdlib.h>
Python TechnologiesDatabasesComputer ProgrammingWeb DevelopmentJava TechnologiesComputer ScienceMobile DevelopmentBig Data & AnalyticsMicrosoft TechnologiesDevOpsLatest TechnologiesMachine LearningDigital MarketingSoftware QualityManagement Tutorials View All Categories ... The stdlib.h header defines four variable types, several macros, and various functions for performing general functions.
🌐
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
Answer (1 of 4): Same as max function in any language. Except C will be much more primitive. a more sophisticated generic rendering would be: max (collection [comparable]): comparable this says that we can take any collection where all the elements are comparable and find the value that is the...