The following #define partially works:
#define OUT(x) \
if(x > 0) cout << "Hello "; \
if(x > 1) cout << x+1
OUT(1) << "message"; // OK
if(0) {
OUT(1) << "message"; // OK, nothing printed
}
if(0)
OUT(1) << "message"; // NO, printed anyway
I understand why it does not work (if(0) applies to if(x > 0) only).
I cannot find a way to make it work. Consider that I cannot put braces in the define, otherwise I will not be allowed to use the insertion operator.
Updated to print “Hello”
It can be done this way (oh the ugliness!):
This is a “standard” comma operator trick that allows additional expressions to be evaluated within the
ifconditional without affecting the branch taken in the end.In this case one expression is added: a ternary operator that evaluates the original condition
x > 0. An expression (not a statement, but this restriction does not matter here) that produces the desired side effect is placed in the “true” branch of the ternary. It does not matter at all what the “false” branch evaluates to, so long as it’s the same type as (or can be implicitly converted to) the result of the “true” branch.Here the “true” branch returns an
ostream&, so the easiest way is to returncoutfrom the “false” branch as well and call it a day.Answer to the original question
In the originally posted case (with
xandy) the macro would bewhich for this specific case could be also written as
See it in action.