问题
#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