how i c++ macro act function?
let's contend reason need macro: macro(x,y). (let's assume there's good reason can't an inline function.) wish macro heed duty relapse value.
example 1: should work expected.
if (x > y)
macro(x, y);
do_something();
example 2: should outcome compiler error.
if (x > y)
macro(x, y);
else
macro(y - x, x - y);
example 3: should not compile.
do_something();
macro(x, y)
do_something();
the nave proceed macro this:
#define macro(x,y) \
cout << "1st arg is:" << (x) << endl; \
cout << "2nd arg is:" << (y) << endl; \
cout << "sum is:" << ((x)+(y)) << endl;
this unequivocally bad fortitude fails 3 examples, i shouldn't need explain why.
ignore macro indeed does, that's point.
now, proceed i many mostly macros combined hang curly braces, this:
#define macro(x,y) \
{ \
cout << "1st arg is:" << (x) << endl; \
cout << "2nd arg is:" << (y) << endl; \
cout << "sum is:" << ((x)+(y)) << endl; \
}
this solves instance 1, since macro matter block. nonetheless instance 2 damaged since put semicolon after macro. creates compiler cruise semicolon matter itself, means else matter doesn't conform any statement! lastly, instance 3 compiles ok, even nonetheless there semicolon, since formula retard doesn't need semicolon.
is there proceed macro pass 3 examples?
note: i am submitting possess answer biased , nonetheless anyone improved fortitude feel giveaway post here, competence some-more votes method. :)
Comments
Post a Comment