宏的实际参数太多?
代码:
#include <iostream>
using namespace std;
#define ADD(x,y) ((x)+(y))
int main( int argc, char** argv )
{
cout << ADD(1,2,) << endl;
return 0;
}
编译器输出:
1>正在编译...
1>main.cpp
1>c:\warn_test\main.cpp(9) : 警告 C4002: 宏“ADD”的实际参数太多
为什么这不是一个错误?
g++ (GCC) 4.2.1 20070719 [FreeBSD]
给出了更合理的(在我看来)输出:
main.cpp:9:18:错误:宏“ADD”传递了 3 个参数,但只需要 2 个
main.cpp:在函数“int main(int, char**)”中:
main.cpp:9:错误:“ADD”未在此范围内声明
虽然我不完全确定编译器认为第三个参数是什么。
编辑:添加了完整的 gcc
输出和版本信息。
Code:
#include <iostream>
using namespace std;
#define ADD(x,y) ((x)+(y))
int main( int argc, char** argv )
{
cout << ADD(1,2,) << endl;
return 0;
}
Compiler output:
1>Compiling...
1>main.cpp
1>c:\warn_test\main.cpp(9) : warning C4002: too many actual parameters for macro 'ADD'
Why isn't this an error?
g++ (GCC) 4.2.1 20070719 [FreeBSD]
gives more reasonable (in my mind) output:
main.cpp:9:18: error: macro "ADD" passed 3 arguments, but takes just 2
main.cpp: In function 'int main(int, char**)':
main.cpp:9: error: 'ADD' was not declared in this scope
Though I'm not entirely sure what either compiler thinks the third argument is.
EDIT: Added complete gcc
output and version info.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
受到 Steve Jessop 评论的启发,我将抛出一个完整的猜测,该猜测与可变参数宏支持有关。
当视觉工作室团队实现可变参数宏时,可能更容易使其成为警告?我注意到在实现代码时存在不同程度的容忍度,例如:
某些编译器会出错、警告或忽略各种情况。我不知道标准是怎么说的。
I'm going to throw out a complete guess, inspired by Steve Jessop's comment that it's related to variadic macro support.
Possibly it was easier to make it a warning when the visual studio team implemented variadic macros? I've noticed varying levels of tolerance when implementing code like:
Some compilers error, warn or ignore the various situations. I don't know what the standards says tho.
您使用
ADD(1,2,)
,注意第二个,
。删除它,它就会编译得很好!@schnaader:你是对的,我读得太快了。对不起。
[编辑]
请提供有关相关编译器的更多详细信息。我使用:g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5,这是我得到的结果:
[edit2]
抱歉,又有点太快了:-)。我看到你用 Visual Studio 标记了它。 VS比g++更宽容。我想——因为在这种情况下很容易解决——它会自动纠正它。
You use
ADD(1,2,)
, note the second,
. Remove that and it will compile just fine!@schnaader: You are right, I read too fast. Sorry.
[edit]
Please provide more details about the compiler in question. I use: g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5, and this is the result I get:
[edit2]
Sorry, again a bit too fast :-). I see you tagged it with visual studio. VS is more tolerant than g++. I suppose that -- because it is easy to resolve in this case -- it automatically corrects it.
我想这在某种程度上是编译器的选择。如果有第三个参数,可能会出现更多问题,但由于没有,您可以争论是否忽略逗号或抛出错误。微软似乎经常更容错(就像在 IE HTML 解析中)。
I guess this is somewhat compiler's choice. If there was a third parameter, it would perhaps be more problematic, but as there isn't, you can argue about just ignoring the comma or throwing an error. Microsoft seems to be more error tolerant often (like in IE HTML parsing).