Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MIN and MAX in C

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.)

like image 221
Matt Joiner Avatar asked Aug 09 '10 04:08

Matt Joiner


People also ask

What is MIN () and MAX ()?

In these examples, you call min() and max() with a list of integer numbers and then with an empty list. The first call to min() returns the smallest number in the input list, -5 . In contrast, the first call to max() returns the largest number in the list, or 9 .

What does Max () do in C?

Say max() function is used to find maximum between two numbers. Second, we need to find maximum between two numbers. Hence, the function must accept two parameters of int type say, max(int num1, int num2). Finally, the function should return maximum among given two numbers.

What kind of functions are MIN and MAX in C?

What kind of functions are min and max in c++? Explanation: The min/max functions are type specific but they will not force everything to be converted to/from floating point. The functions that will force everything to be converted to/from floating point are fmin/fmax. 3.

What library is min in C?

However, both max() and min() are already part of the C++ standard library, in the <algorithm> header ( #include <algorithm> ).


1 Answers

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.

like image 97
David Titarenco Avatar answered Sep 20 '22 15:09

David Titarenco