0

I don't understand why the following code won't compile:

#include <iostream>
#define SHORT_NAME 4;

int func(int arg)
{
    return arg;
}

int main()
{
    return func(SHORT_NAME); // Error: expected a ')'
}

Should I be using const int SHORT_NAME = 4 on line 2 instead?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dan Stevens
  • 6,392
  • 10
  • 49
  • 68

3 Answers3

8

Remove the semi-colon from the macro SHORT_NAME as after preprocessing it is expanded to:

 return func(4;);

Or use const int as you suggest in the question. See "static const" vs "#define" vs "enum" for a discussion on macros vs const.

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
3

The preprocessor expands the MACRO name. So this:

return func(SHORT_NAME);  

becomes this:

return func(4;); 

that is definitely a syntax error, isn't?

So if you define the MACRO without ; then it will work:

#define SHORT_NAME 4  //without ;

Should I be using const int SHORT_NAME = 4 on line 2 instead?

YES. Go for it. Macros are evil, anyway (in most cases).

Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

You don't need the semicolon in your define. Write this instead

#define SHORT_NAME 4

But using const int is definitely a better choice when using C++.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198