Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define causes an "expected primary-expression" error

#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?

like image 310
Jordan Avatar asked Sep 08 '12 01:09

Jordan


2 Answers

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)

like image 72
Adrian Cornish Avatar answered Oct 14 '22 03:10

Adrian Cornish


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.

like image 45
Fred Larson Avatar answered Oct 14 '22 01:10

Fred Larson