表达式中的宏未按预期工作

Macro in an expression is not working as expected

我有一个简单的宏来添加 2 个变量,但没有按预期工作。

#include <iostream>
using namespace std;
#define ADD(x,y) (x+y);

int main() {
    int a = 10;
    int b = 1;
    int c = ADD(a,b)+1; //c=11 - NOT EXPECTED
    int c = 1+ADD(a,b); //c=12 - EXPECTED

    cout<< c;
}

在上面的代码中,当我在宏的开头添加 1 时,它给出了预期的输出。但是,如果我在末尾加 1,它实际上并不是加 1。

为什么会出现这种行为? 据我所知,当使用宏时,编译器只会在编译期间用令牌字符串替换宏。如果是这样,在这两种情况下,输出应该是相同的。

第一种情况:c = (a+b)+1 第二种情况c = 1+(a+b)

把宏末尾的分号去掉,写成这样

#define ADD(x,y) (( x ) + ( y ))

否则例如这一行

int c = ADD(a,b)+1;

相当于

int c = (a + b); +1;

即它包含变量声明c和语句

+1;

没有效果。