I'm having lots of trouble with this task:
I have to design a macro to calculate the median of three numbers. It must work regardless of the variable type.
I have tried and used conditional expressions but the code gets very messy, hardly readable and buggy. On the other, hand I can't use functions as I cannot make assumptions about the variable type.
The macro should look like
#define MEDIAN(a,b,c) --macro definition ---
Any clue as to how to solve this as elegantly as possible would be immensely appreciated. Thanks
I wonder who told you that you should use a macro for this task, because that person told you to use an "evil" feature of C++. I trust you have discovered in what way it is evil.
Your object cannot work regardless of the type. It can only work on types that have an overload for one of the operators (or two, such as < and >). I actually do recommend a chain of if-else statements for this. Try something like if(a>b && b<c) /*b is greatest*/ elseif....
I suspected that I would end up with lots of ifs and elses.
I know that in C++ there are better ways of doing this, with templates for example.
The thing is, I'm learning C with all its subtleties now, the reason being you have to be absolutely fluent with C for Linux system programming and lots of embedded systems. That is my goal.
Thanks m4ster, that's exactly what I was trying to achieve as I was getting lost with the parentheses.
I know the advantages of C++ and I know quite a bit of the language, in fact I learned it before C. I just decided to study the latter a bit more in depth for the above mentioned reasons.
@Albatross
You're right, if you know C++ you can read C syntax. However, one of the main differences is that C makes a much heavier use of macros and the preprocessor. That's why I need to practise these "evil" features.