C中宏的意外行为

Ins*_*der 0 c macros

如何执行以下代码(除了第二行中的分号外,代码相同)

此代码预计会执行,也会执行.

#include<stdio.h>
#define SWAP(a, b) int t; t=a, a=b, b=t  //note here is no semi-colon at the end
int main()
{
    int a=10, b=12;
    SWAP(a, b);
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是预计以下不会SWAP(a, b)被替换为int t; t=a, a=b, b=t;;.所以两个分号应该产生错误!

#include<stdio.h>
#define SWAP(a, b) int t; t=a, a=b, b=t;  //note the semi-colon here
int main()
{
    int a=10, b=12;
    SWAP(a, b);
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 7

迷路分号变为空语句,在C中完全合法.

您可以通过在代码中添加包含十几个分号的行来证明这一点.

另外,你的宏写得更好:

#define SWAP(a, b) do { int t = a; a = b; b = t; } while (0)
Run Code Online (Sandbox Code Playgroud)

如果您尝试在单个代码块中进行两次不同的交换,则效果会更好.