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.
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.
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.
+2147483647. Defines the maximum value for an int. UINT_MAX. 4294967295. Defines the maximum value for an unsigned int.
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!
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.
*/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With