Too many actual parameters for macro?

故事扮演 提交于 2019-12-10 17:19:10

问题


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.


回答1:


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:

test.cpp:9: error: macro "ADD" passed 3 arguments, but takes just 2
test.cpp: In function ‘int main(int, char**)’:
test.cpp:9: error: ‘ADD’ was not declared in this scope

[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.




回答2:


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:

#define MACRO(...) my_func(true, __VA_ARGS__);

MACRO(1,,2); // Missing argument
MACRO(1,); // missing tail
MACRO(); // no arguments

Some compilers error, warn or ignore the various situations. I don't know what the standards says tho.




回答3:


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).



来源:https://stackoverflow.com/questions/5248599/too-many-actual-parameters-for-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!