I am trying to code a simple macro which based on a condition either calls break
or continue
in the loop in which it is called. Below is the code:
#include <iostream>
#define BC_IF_EVEN(BC) if(i % 2 == 0) BC
using namespace std;
int main() {
int i = 0;
while(i++ < 30) {
if(i < 15)
BC_IF_EVEN(continue);
else
BC_IF_EVEN(break);
cout << i << " ";
}
cout << endl;
}
The output that I am looking for is: 1 3 5 7 9 11 13 15
, but the above code outputs: 1 3 5 7 9 11 13 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
because the else
condition in main()
gets applied to the if
condition in the BC_IF_EVEN
macro.
A simple fix is to put scope braces for the if
condition in main()
, but I do not want to enforce that because the user should be allowed to code in regular way.
N.B. I cannot put a do { .. } while(false)
loop in the macro (which is a standard trick to allow semicolons after macro calls in conditionals because the break
and continue
sent via BC
get applied to this inner loop.
Is there an easy way to get the required output without modifying the main()
function?