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,438
  • 68
  • 55
  • 126
Dan Stevens
  • 5,923
  • 10
  • 49
  • 64

3 Answers3

7

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
  • 117,013
  • 19
  • 199
  • 247
2

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
  • 341,464
  • 111
  • 648
  • 831
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
  • 69,448
  • 7
  • 95
  • 188