#define causes an “expected primary-expression” error

对着背影说爱祢 提交于 2020-01-02 05:08:07

问题


#define N 10;

int main()
{
    int x;

    for (int i=0; i<N; i++)
        x = i;

    return 0;
}

Result of compiling this in g++:

test-define.cpp: In function ‘int main()’:
test-define.cpp:7:22: error: expected primary-expression before ‘;’ token
test-define.cpp:7:22: error: expected ‘)’ before ‘;’ token
test-define.cpp:7:24: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
test-define.cpp:7:24: note: (if you use ‘-fpermissive’ G++ will accept your code)
test-define.cpp:7:27: error: expected ‘;’ before ‘)’ token

But it compiles fine when I change line 7 to for (int i=0; i<10; i++).

Why is this and how can I use the #define directive to accomplish what I want?


回答1:


Remove the semicolon - you will be good - the semicolon is included in the substitution

Sometimes it is useful to get the compiler to run the preprocessor only. With gcc/g++ you can do something like

gcc -E file.c > result.txt

This will show you how the macro expanded (hint start at the end of the file and work up)




回答2:


I recommend replacing the macro with a constant:

const int N = 10;

It's best to avoid macros when you can. Macros don't have any scope. They are a global text substitution. The compiler never sees them, so if you use a debugger it won't know about them. There are probably other reasons not to use them that I'm forgetting.



来源:https://stackoverflow.com/questions/12327358/define-causes-an-expected-primary-expression-error

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