#define causes an "expected primary-expression" error

10,287

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

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

Share:
10,287
Jordan
Author by

Jordan

Updated on June 25, 2022

Comments

  • Jordan
    Jordan almost 2 years
    #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?

  • Adrian Cornish
    Adrian Cornish over 11 years
    @Jordan Helped me many many times over the years especially where you include some file that does some weird #define like #define result int and you have a local var called result
  • Adrian Cornish
    Adrian Cornish over 11 years
    Very true - should have said that myself, and you should add the reason why consts are better than #define