首页 > 解决方案 > 宏不允许在其参数中使用逗号分隔的定义吗?

问题描述

我发现了一个有趣的代码片段,它的工作方式非常奇怪

#include <iostream>
#include <cstdio>
#define DEBUG_CMD(cmd)                                                                             \
    do {                                                                                           \
        cmd;                                                                                       \
    } while (false)

using namespace std;

int main()
{
    cout<<"Hello World";
    DEBUG_CMD({
        int x = 1;
        int y = 1;
        //int x= 1, y =1; // enable this and comment two lines above will yield an error
        printf("x: %d y: %d\n", x, y);
    });

    return 0;
}

当我分别定义 x, y 时,代码可以运行。但是当我在逗号分隔的同一语句中定义 xy 时,编译器会抱怨语法错误。

main.cpp:26:6: error: macro "DEBUG_CMD" passed 2 arguments, but takes just 1
     });
      ^
main.cpp: In function ‘int main()’:
main.cpp:21:5: error: ‘DEBUG_CMD’ was not declared in this scope
     DEBUG_CMD({
     ^~~~~~~~~

我想知道这里发生了什么。

提示:你可以在https://onlinegdb.com/ryUuyZEmO编译它,它也会给你同样的错误。

标签: c++macros

解决方案


推荐阅读