简体   繁体   中英

c++ variable does not name a type in macro

Have this code:

#include <iostream>

int a=0;

#define F(f) \
  int t##f(int, int);\
  a ++;\
  int t##f(int i, int j)  

F(nn) {
    return i*j;
}

int main() {
 int b = tnn(3, 8);
 std::cout << a << b;
}

Got error when compiling:

7:3: error: 'a' does not name a type
10:1: note: in expansion of macro 'F'

Why isn't a visible in macro at the position it expands?

Look at the expansion of the macro:

F(nn) becomes

int tnn(int, int);
a++;
int tnn(int i, int j) {
  return i * j;
}

The variable 'a' is being incremented outside a function which is a syntax error.

Like the other answer said, you cannot execute statements wherever you please; statements must be inside a function in order to be valid.

There are a few things that can go in the global scope :

  1. Namespace declaration and definitions
  2. Global variable declarations
  3. Function prototypes and definitions
  4. Template and class declarations and definitions
  5. Preprocessor directives

Things that must be in function scope:

  1. Control statements such as if and for
  2. Labels
  3. Function calls

Finally, the above lists are not all inclusive.

Your macro ( in the nn case) expands to:

int a=0;

int tnn(int, int); a ++; int tnn(int i, int j)  {
    return i*j;
}

int main() {
 int b = tnn(3, 8);
 std::cout << a << b;
}

There is no global scope in C++. That is only in scripting languages. Execution order is an initialization library-- something like crt0.s which constructs your run time envioronment. Then initialize global variables ( this part can get very complicated ) then run main.

You statement fails simply because you cannot put arbitrariy executable code where the macro is expanded.

PS: Bjarne says don't use macros. In fact he create const, inline and to some degree templates so that you can avoid macros. Macros are evil!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM