Reputation: 3855
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?
Upvotes: 3
Views: 2170
Reputation: 443
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!!!!
Upvotes: 6
Reputation: 680
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:
Things that must be in function scope:
Finally, the above lists are not all inclusive.
Upvotes: 7