C / C ++宏,用于中断或继续

Joh*_*ine 0 c c++ c-preprocessor preprocessor-directive

我正在尝试编写一个简单的宏,该宏基于调用的条件breakcontinue在调用它的循环中的条件。下面是代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找的输出是:1 3 5 7 9 11 13 15,但是上面的代码输出:1 3 5 7 9 11 13 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30因为elsein中的条件main()被应用于宏中的if条件BC_IF_EVEN

一个简单的解决方法是将if条件的范围括号放在中main(),但我不想强制执行该操作,因为应该允许用户以常规方式进行编码。

注意:我不能do { .. } while(false)在宏中放入循环(这是在条件调用宏之后允许使用分号的标准技巧,因为breakcontinue发送通过BC应用于此内部循环。

有没有一种简单的方法就可以在不修改main()功能的情况下获得所需的输出?

joh*_*ohn 5

#define BC_IF_EVEN(BC) if (i % 2 != 0); else BC
Run Code Online (Sandbox Code Playgroud)

但是为什么呢?