I came across a interview question which reads as follows:
"Write a simple C/C++ Macro to find maximum of two numbers without using std library or ternary operator".
I need your help in solving this. I know this is trivial but I couldn't find it. So, posting it here.
#include<iostream>
#define max(x,y) /*LOGIC HERE*/
using namespace std;
void main()
{
int a = 98453;
int b = 66394;
cout<<max(a,b);
}
Use Boolean operations to get 0 or 1 and then just add them up:
#define max(x,y) (((int)((x)<(y)) * (y)) + ((int)((y)<=(x)) * (x)))
#include <iostream>
#define max(x, y) [a = x, b = y](){ if (a<b) return b; else return a; }()
int main() {
using namespace std;
int a = 10;
int b = 20;
cout << max(10, 20);
cout << max(a, b);
};
a solution just for fun : > compiled with c++14
would blow up if x, y has different types
#define max(x,y) (x+y + abs(x-y))/2
gives you what you are looking for. This works because abs(x-y) = max(x,y) - min(x,y)
. So, you can rewrite the expression as follows
(x + y) + abs(x-y) = max(x,y) + min(x,y) + max(x,y) - min(x,y)
= 2*max(x,y)
As pointed out in the comments, using abs
might violate the conditions what you have asked for.
#define max(x, y) x - ((x-y) & ((x-y) >> 31))
This assumes x and y are 32 bit.
This works by the fact that the most-significant bit of a negative integer is 1.
Thus if x-y is negative (y is greater than x) then x - (x - y) = y.
If x-y is positive then x is greater than y, the most significant bit is zero and thus x - 0 = x.
The 31 represents the total # of bits of the variable - 1. (thus the most significant bit).
I imagine this is what they're looking for since it doesn't use comparisons.
Aww, so many nice solutions. I have another one exploiting that booleans convert to zero and one:
#define CONDITION(c, t, f) (c * t + (1 - c) * f)
#define MAX(a, b) CONDITION(a > b, a, b)
Nearby, I'm deliberately ALL_UPPERCASING this evil macro machinery. I'd say this is the actual point you should have raised in an interview.
Another crazy C++11-only approach, and cheating slightly with an extra struct
declaration (could use a std::array
if libraries were allowed) - for whatever it's worth (not much!)...
struct Max { int n_[2]; };
#define max(x,y) (Max{(x),(y)}.n_[(x) < (y)])
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