Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Macro for minimum of two numbers

I want to make a simple macro with #define for returning the smaller of two numbers.

How can i do this in C ? Suggest some ideas, and see if you can make it more obfuscated too.

like image 388
VaioIsBorn Avatar asked Mar 16 '10 22:03

VaioIsBorn


People also ask

How do you find the minimum of two numbers in C?

Program Explanationcheck whether num1 is smaller than num2 using if statement. if num1 is smaller print num1 using printf statment, else check whether num2 is smaller than num1 using elseif statement. If num2 is smaller print num2 using printf statement, else print num1 and num2 are equal using printf statment.

Is there any MIN function in C?

min is indeed an inline function that returns the smallest of “a” and “b” implemented with GNU C smart macros. They can be any numeric values, including pointers to almost the same base type, and then they can be an integer or floating-point values.

What is #define MAX in C?

+2147483647. Defines the maximum value for an int. UINT_MAX. 4294967295. Defines the maximum value for an unsigned int.

Is there MIN and MAX function in C?

The min and max functions are declared in the standard C++ algorithm header by the C++ Standard Template Library (STL). The fmin and fmax functions are included in the standard C math. h header according to the C standard (C99). Thank you very much in advance!


2 Answers

Typically:

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

Be warned this evaluates the minimum twice, which was the reason for disaster in a recent question.

But why would you want to obfuscate it?


This one stores the result in a variable, and only evaluates each argument once. It's basically a poor-mans inline function + declaration:

#define min(t, x, a, b) \
            t x; \
            { \
                t _this_is_a_unique_name_dont_use_it_plz_0_ = a; \
                t _this_is_a_unique_name_dont_use_it_plz_1_ = b; \
                x = _this_is_a_unique_name_dont_use_it_plz_0_ < \  
                    _this_is_a_unique_name_dont_use_it_plz_1_ ? \
                    _this_is_a_unique_name_dont_use_it_plz_0_ : \  
                    _this_is_a_unique_name_dont_use_it_plz_1_ ; \
            }

Use it like:

min(int, x, 3, 4)
/* x is an int, equal to 3
  Just like doing:

  int x = min(3, 4);

  Without double evaluation.
*/
like image 87
GManNickG Avatar answered Sep 30 '22 11:09

GManNickG


And, just for the hell of it, a GNU C example:

#define MAX(a,b) ({ \
    typeof(a) _a_temp_; \
    typeof(b) _b_temp_; \
    _a_temp_ = (a); \
    _b_temp_ = (b); \
    _a_temp_ = _a_temp_ < _b_temp_ ? _b_temp_ : _a_temp_; \
    })

It's not obfuscated, but I think this works for any type, in any context, on (almost, see comments) any arguments, etc; please correct if you can think of any counterexamples.

like image 31
David X Avatar answered Sep 30 '22 13:09

David X