In this snippet, I can't understand what the FUNCTION(func,pred) is supposed to be doing.
#define FUNCTION(func,pred)\
void func(int& a, int x){ \
if(!(a pred x)) a = x; \
}
I also can't understand this:
FUNCTION(minimum, <)
FUNCTION(maximum, >)
Can somebody explain please?
-
5What part of the code confuses you?Thomas Matthews– Thomas Matthews2016年05月20日 17:10:19 +00:00Commented May 20, 2016 at 17:10
-
2It would be helpful if you went through and explain how you think it works and we can correct you if that is incorrect/there is missing understanding.NathanOliver– NathanOliver2016年05月20日 17:11:06 +00:00Commented May 20, 2016 at 17:11
-
Hello Thomas, I am being confused about of "FUNCTION (func,pred)" of the preprocessor and two FUNCTIONs just above int main().ethelake– ethelake2016年05月20日 17:11:55 +00:00Commented May 20, 2016 at 17:11
-
Use the macro, and then run the file though the preprocessor and see that the macro invocation is replaced with. All good compilers have options to stop after running the preprocessor.Some programmer dude– Some programmer dude2016年05月20日 17:12:08 +00:00Commented May 20, 2016 at 17:12
-
Hello Nathan, thanks for the feedback I should edit my questions :)ethelake– ethelake2016年05月20日 17:12:36 +00:00Commented May 20, 2016 at 17:12
2 Answers 2
The preprocessor substitutes all tokens: FUNCTION(func,pred) with
void func(int& a, int x){
if(!(a pred x)) a = x;
}
Thus, defining a function func with a binary operator as pred. So, when you write this:
FUNCTION(minimum,<)
The preprocessor replaces that with:
void minimum(int& a, int x){
if(!(a < x))
a = x;
}
Same thing happens with:
FUNCTION(maximum,>)
produces:
void maximum(int& a, int x){
if(!(a > x))
a = x;
}
...and so on..
1 Comment
The macro FUNCTION is defining a function with the name func. For example:
FUNCTION(minimum, <)
Would define a function like so:
void minimum(int& a, int x) {
if(!(a < x)) {
a = x;
}
}
Macros are a method of code generation. The author of this code obviously felt it was too arduous to write out this 2 line function and instead confuse everyone with macros.
This is definitely a case where macros harm (readability) rather than help. I don't recommend doing this for such basic functions.