c++ - 宏不允许在其参数中使用逗号分隔的定义吗?
问题描述
我发现了一个有趣的代码片段,它的工作方式非常奇怪
#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编译它,它也会给你同样的错误。
解决方案
推荐阅读
- android - 在 Xamarin.Forms 中创建多个单独的弹出式项目的最佳方法是什么?
- microservices - 使用事件驱动的微服务架构在 Web 应用程序中显示数据
- python - 如何绘制二维数组
- teradata - 根据 teradata 中的某些条件将多行连接成一列
- c - 为什么 getaddrinfo() 总是导致分段错误?
- c# - 在本地调试 Nuget 包
- ios - 如何附加对象Realmswift的列表属性
- javascript - 将 sqrt sysmbol 附加到 D3.js 生成的 svg 图表
- amazon-web-services - 如何在 AWS Lambda 中加载 AWS Cloudformation 的输出?
- flutter - 在 Flutter 中使用 ToggleButton 在两个有状态的小部件之间切换,同时保持在同一位置