C Macro for minimum of two numbers - c

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.

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.

Sure, you can use a #define for this, but why would you want to? The problem with using #define, even with parentheses, is that you get unexpected results with code like this (okay, you wouldn't actually do this, but it illustrates the problem).
int result = min(a++, b++);
If you're using C++ not C, surely better to use an inline function, which (i) avoids evaluating the parameters more than once, and (ii) is type safe (you can even provide versions taking other types of value, like unsigned, double or string).
inline int min(int a, int b) { return (a < b) ? a : b; }

I think this method is rather cute:
#define min(a, b) (((a) + (b) - fabs((a) - (b))) * 0.5)

I want to make a simple macro with #define for returning the smaller of two numbers.
I wanted to add a solution when the numbers are floating point.
Consider when the numbers are floating point numbers and one of the numbers is not-a-number. Then the result of a < b is always false regardless of the value of the other number.
// the result is `b` when either a or b is NaN
#define min(a, b) (((a) < (b)) ? (a) : (b))
It can be desirable that the result is as below where "NaN arguments are treated as missing data". C11 Footnote #242
a NaN | b NaN | a < b | min
-------+---------+---------+---------------
No | No | No | b
No | No | Yes | a
No | Yes | . | a
Yes | No | . | b
Yes | Yes | . | either a or b
To do so with a macro in C would simple wrap the fmin() function which supprts the above table. Of course code should normally used the fmin() function directly.
#include <math.h>
#define my_fmin(a, b) (fmin((a), (b))
Note that fmin(0.0, -0.0) may return 0.0 or -0.0. They both have equal value.

If I were just trying to lightly obfuscate this I would probably go with something like:
#define min(a,b) ((a) + ((b) < (a) ? (b) - (a) : 0))
I think Doynax's solution is pretty cute, too. Usual reservations for both about macro arguments being evaluated more than once.

For slightly obfuscated, try this:
#define MIN(a,b) ((((a)-(b))&0x80000000) >> 31)? (a) : (b)
Basically, it subtracts them, and looks at the sign-bit as a 1-or-0.
If the subtraction results in a negative number, the first parameter is smaller.

Related

Using Macros in a program that calculates the midrange of three values

I am trying to create a program that uses macros for determining the mid-range for three values. The midrange is defined as:
midrange(a, b, c) = (min(a, b, c) + max(a, b, c)) / 2
For example:
midrange(3, 10, 1) = (min(3, 10, 1) + max(3, 10, 1)) / 2
= (1 + 10) / 2
= 11 / 2
= 5.5
I am still new to programming, and I am not sure if the syntax I am using for macro definitions is correct. My first question is, can I define a macro in the main function? My second question, should I use curly braces, normal parenthesis, or nothing at all for the body of the macro, that is, the replacement list?
This is what my program looks like for calculating the midrange of three integer values:
#include <stdio.h>
#define MIN(A, B) {(A) < (B) ? (A) : (B);}
#define MAX(A, B) {(A) > (B) ? (A) : (B);}
int main(){
//scans the three values
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
int min = MIN(MIN(a, b), c);
int max = MAX(MAX(a, b), c);
//defines new macro for calculating the midrange
//is this allowed/correct formatting and syntax?
#define MIDRANGE((min + max) / 2);
/* initializes variable mrange to equal to the value returned
function-like macro, MIDRANGE */
double mrange = MIDRANGE((min + max) / 2);
printf("The mid-range is: %lf", mrange);
return 0;
}
The reason why I declared the variable mrange as a double is because I want the value of the MIDRANGE macro to be precise, meaning that it will keep the decimal places after the division by 2 in the equation.
Any help is appreciated:)
You can declare a macro anywhere in the code, but unless you have a very specific reason to restrict its usage to a function, it typically appears in the beginning of the .c file or in a .h file.
Macros work by substitution. So if you have something similar to the following:
#define MIN(A, B) {(A) < (B) ? (A) : (B);}
int main(void)
{
int min = MIN(MIN(a, b), c);
}
It will be preprocessed into:
int min = {({(a) < (b) ? (a) : (b);}) < (c) ? ({(a) < (b) ? (a) : (b);}) : (c);};
You can see this by yourself, if you are using GCC, with the command gcc -E source.c. This is obviously not what you wanted, and it will give you a compilation error.
We never use ; at the end of macros, neither put them in blocks. To avoid unexpected operator association with complicated expressions, we guard macro parameters and the whole macro within parentheses.
Your MIN macro should look somewhat like this:
#define MIN(A, B) ((A) < (B) ? (A) : (B))
Finally, there are two things going on with your MIDRANGE macro. First, it should be taking arguments, like you did with MIN. Ideally, it should take three arguments; after all, the whole reason to make it a macro is so that the macro user won't have to calculate everything. Second, if you want the result to be a floating-point number, you should divide by 2.0, not 2.
Here's my first suggestion:
#define MIDRANGE(A, B, C) ((MIN(MIN(A, B), C) + MAX(MAX(A, B), C)) / 2.0)
However, why is this a macro? Make it a function. It's more readable, and easier to mantain. So here's my second suggestion:
double midrange(int a, int b, int c)
{
int min = MIN(MIN(a, b), c);
int max = MAX(MAX(a, b), c);
return (min + max) / 2.0;
}
regarding:
#define MIN(A, B) {(A) < (B) ? (A) : (B);}
#define MAX(A, B) {(A) > (B) ? (A) : (B);}
Lets remember that a macro is nothing more than a direct text replacement.
So looking at:
int min = MIN(MIN(a, b), c);
results in:
int min = { {(a) < (b) ? (a) : (b);} < (c);};
as is obvious from the above,
min is outside the braces '{' and '}' so will be difficult to assign to
the resulting statement contains two spurious ';' characters, which is what the compiler is complaining about
Suggest:
#define MIN( A, B ) ((A) < (B)) ? (A) : (B)
Similar considerations exist for the MAX macro

what is the difference of these two macro max?

writing leetcode
I use the macro like this:
#define max(a,b) ((a) > (b))?(a):(b)
it is wrong,when i change the macro like this,it's right
#define max(a,b) (((a) > (b))?(a):(b))
can't figure out why does this different.Here is the code,you can check it out.
#define UNBALANCED 99
#define max(a,b) (((a) > (b))?(a):(b))
int getHeight(struct TreeNode * root)
{
if(NULL == root)
return -1;
int l = getHeight(root->left);
int r = getHeight(root->right);
if(UNBALANCED == l || UNBALANCED == r || abs(l-r) > 1)
return UNBALANCED;
return 1 + max(l,r);
}
bool isBalanced(struct TreeNode* root)
{
if(NULL == root)
return true;
return getHeight(root) != UNBALANCED;
}
that is different with The need for parentheses in macros in C
The former fails to isolate the macro replacement from neighboring operands. For example:
1 + max(a, b)
expands to:
1 + ((a) > (b))?(a):(b)
and that groups as:
(1 + ((a) > (b))) ? (a) : (b)
Then (1 + ((a) > (b))) is always nonzero, so (a) is always chosen.
To prevent this, a macro that expands to an expression should use parenthesis around its entire expression to prevent its parts from grouping with neighboring operands.
The second version of your macro has extra parentheses which make the expression ((a) > (b))?(a):(b) evaluated as a whole. More code would be needed to explain exactly why the first one is wrong in your case. Also, see this.
Arguably both of them are incorrect; what if you wanted to use your macro like:
MAX(i++, j++)
The resulting ternary-operator expression from your examples cause whichever expression is smaller to be evaluated twice. Yowch! Since you (and most future readers) likely use GCC or clang, here's a better example with some compiler extensions (__typeof__ and statement expressions) that both of them support.
#define MAX(a, b) ({ __typeof__ (a) a__ = (a); \
__typeof__ (b) b__ = (b); \
(a__ > b__) ? a__ : b__; })

find min(a,b,c) or max(a,b,c) with using #define macro preprocessor in c

this is the question what asked in my exam is: "write cource code of min(a,b,c) with macros in c language."
#define min(a,b,c) ((a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c)))
is there better way to solve min/max(x,y,z) problem?
Your solution, and all portable macro-based ones, are a good reason why the use of macros should be limited as much as possible. Nowadays, I pretty much use them for little more than conditional compilation.
In terms of defining constants, you are better off with enumerations.
In terms of function-like macros, you're far better off using functions which you can suggest to the compiler to be made inline, or just rely on the compiler to figure that out (they're usually pretty good at that).
The reason why function-like macros are a bad idea is because, being simple text substitution, the sequence:
#define mymax(a, b) (a) > (b) ? (a) : (b)
int x = mymax(y++, complexFunction());
will actually evaluate y++ and/or call complexFunction() more than once, something a real function would not do.
By all means use them provided you understand the limitations. Me, I'll rely on the compiler doing the right thing for functions so that I don't have to worry about the dark corners of C too much :-)
Yes. Write functions.
int min2( int x, int y ) { return x < y ? x : y; }
int min3( int x, int y, int z ) { return min2( x, min2( y, z ) ); }
If you wish for pretty, you can write some variadic macros that choose the correct function based on the number of arguments. Those are a bear to write, though.
If you wish to stick with only macros, your choices are much less friendly. Ajay B’s solution (fixed as per commentary) works well.
GCC supports some nice extensions that eliminate re-evaluation issues:
#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; })
You can then easily write any n-ary macro you wish that does not suffer from parenthetical or re-evaluation horrors.
#define max3(a,b,c) max(a,max(b,c))
I think the key point you missed in the question is "macros" not and macro. You can simplify this a lot if you break it down further as follows -
#define min2(a, b) ((a) < (b) ? (a) : (b))
#define min(a, b, c) (min2(min2((a), (b)), (c)))
This is also much easier to comprehend.

x-macro conditional error - number comparison

I would like to generate compile time error for X-macro for all X(a, b) where a > b
/* X(a, b) */
#define LIST \
X(10, 20) \
X(5, 20) \
X(30, 20) \
X(1, 20)
So, generate error for X(30, 20)
Is this possible in C?
EDIT: example usage
For me, left number is for example sizeof of some large struct and right number is fixed space to store this struct. If the struct is bigger then available space, I need compiler to generate error.
//e.g.
X(sizeof(struct conf), 2*PAGE)
Yes, here's a proof of concept:
#pragma push_macro("X")
#undef X
#define X(a,b) typedef int x[(a>b)?-1:1];
LIST
#pragma pop_macro("X")
So, we define X to define a type of array of ints, with either -1 or 1, depending whether a is greater than b. If it is, the array of -1 elements will cause an error.
If using C11, the typedef line can be done using static_assert(a<=b) from assert.h
It is possible in C11 by using the _Static_assert keyword:
#define X( a , b ) _Static_assert( a <= b , "Error!" )
Note that expressions a and b must be constant.

The best way to define a "between" macro in C

What's the best way to define a between macro, which is type generic (char,int,long)
which will return true if a number is between to other numbers inputted.
I'm tried to google it, but I didn't find anything.
Edit: The order of the two boundaries given shouldn't matter. so it can be more general.
If you do something like:
#define BETWEEN(a, b, c) (((a) >= (b)) && ((a) <= (c)))
you are going to have problem with the double evaluation of a. Think what would happens if you do that with a functions that has side effects...
you should instead do something like:
#define BETWEEN(a, b, c) ({ __typeof__ (a) __a = (a); ((__a) >= (b) && ((__a) <= (c)) })
(edited because the result should not depend of the order of b and c):
#define BETWEEN(a, b, c) \
({ __typeof__ (a) __a = (a);\
__typeof__ (b) __b = (b);\
__typeof__ (c) __c = (c);\
(__a >= __b && __a <= __c)||\
(__a >= __c && __a <= __b)})
Firstly, don't use macros for things like this - use functions (possibly inline).
Secondly, if you must use macros, then what's wrong with e.g.
#define BETWEEN(x, x_min, x_max) ((x) > (x_min) && (x) < (x_max))
?
As per your subsequent edit, if you don't know the ordering of x_min and x_max then you could do this:
#define BETWEEN2(x, x0, x1) (BETWEEN((x), (x0), (x1)) || \
BETWEEN((x), (x1), (x0)))
The usual caveats about macros and side-effects etc apply.
Edit: removed space between macro & arguments for compilation
If all types are the same, how about:
/* Check if 'a' is between 'b' and 'c') */
#define BETWEEN(a, b, c) (((a) >= (b)) && ((a) <= (c)))
Note that if the types of a, b and c above are different, the implicit type conversions of C might make it wrong. Especially if you mix signed and unsigned numbers.
+1: A not-so-trivial question, since it involves the problem of the evaluation of macro parameters. The naive solution would be
#define BETWEEN(x,l1,l2) (((x) >= (l1)) && ((x) <= (l2)))
but "x" is evaluated twice, so there may be problems if the expression has side effects. Let's try something smarter:
#define BETWEEN(x,l1,l2) (((unsigned long)((x)-(l1))) <= (l2))
Very very tricky and not so clean, but...
#define BETWEEN_MIN(a, b) ((a)<(b) ? (a) : (b))
#define BETWEEN_MAX(a, b) ((a)>(b) ? (a) : (b))
#define BETWEEN_REAL(val, lo, hi) (((lo) <= (val)) && ((val) <= (hi)))
#define BETWEEN(val, hi, lo) \
BETWEEN_REAL((val), BETWEEN_MIN((hi), (lo)), BETWEEN_MAX((hi), (lo)))
See code running: http://ideone.com/Hb1vP
If I understand correctly, you will need 3 numbers, the upper limit, the lower limit and the number you're checking, so I would do it like this:
#define BETWEEN(up, low, n) ((n) <= (up) && (n) >= (low))
This assumes the between is inclusive of the upper and lower limits, otherwise:
#define BETWEEN(up, low, n) ((n) < (up) && (n) > (low))

Resources