Updated to print "Hello"
It can be done this way (oh the ugliness!):
#define OUT(x) if((x > 0 ? cout << "Hello " : cout), x > 1) cout << x+1
This is a "standard" comma operator trick that allows additional expressions to be evaluated within the if
conditional 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 return cout
from the "false" branch as well and call it a day.
Answer to the original question
In the originally posted case (with x
and y
) the macro would be
#define OUT(x) if((x > 0 ? y = x : 0), x > 1) cout << x+1
which for this specific case could be also written as
#define OUT(x) if((y = x > 0 ? x : y), x > 1) cout << x+1
See it in action.