Maximum value C++ using #define

Jul 20, 2013 at 1:12pm
Hello,
To compare between tow values and return the largest value between them can be done by the following code:
#define getmax(a,b) ((a)>(b)?(a):(b))
and for three number is
#define getmax(a, b,c) ((a>b)?((a>c)?a:c):((b>c)?b:c))

My question is how to do it to compare between 4 numbers, and five numbers. Besides how to do it for 4 numbers to find the minimum value.
Note: It must be with macro.

Jul 22, 2013 at 3:54pm
You don't need a separate macro for 3 or more .
#define getmax(a,b) ((a)>(b)?(a):(b)) is enough.
Jul 22, 2013 at 4:15pm
You can't have multiple macros with the same name. If you want to have macros taking different number of arguments you will have to give them different names.

If getmax is defined as above taking two arguments you can use getmax 2 times to get the max of three values getmax(getmax(a, b), c);. When defining the macros you can also use this technique.

1
2
3
4
#define getmax3(a,b,c) getmax(getmax(a,b),c)
#define getmax4(a,b,c,d) getmax(getmax3(a,b,c),d)
#define getmax5(a,b,c,d,e) getmax(getmax4(a,b,c,d),e)
...
Jul 22, 2013 at 4:40pm
I am sorry I did not make my question clear. Those codes are two separate programs; the first to compare two values, and the second is to compare three, if I want to add d value, how the code can be modified to execute and run the program.
Topic archived. No new replies allowed.