Reputation: 15294
Can I use define in a function scope? Such as:
void run() {
#define auto BOOST_AUTO
auto i = v.begin();
//...
}
Is the define still valid after the function? Can I make it local to the function? (Please don't tell me to use C++11)
Upvotes: 3
Views: 532
Reputation: 16328
The scope (within the pre-processor) of a macro is from its definition point to either a corresponding #undef
or the end of the translation unit. The pre-processor does not know anything about functions or other structures in the code.
Upvotes: 3
Reputation: 21367
#define
s don't keep an own scope as functions do. They are naively replaced by the preprocessor.
#define
ing keywords leads to undefined behaviour.
This means it is up to the compiler what to do. I assume yet that most compilers will get your idea and replace all occurrences of auto
with BOOST_AUTO
.
Upvotes: 1
Reputation: 172458
Yes you can use but you also need a #undef
directive where you function scope ends.
In your case it would result in an undefined behavior as you are trying to define keyword.
Upvotes: 1
Reputation: 1
Can I use define in a function scope?
Yes you can use preprocessor directives anywhere. The cpp isn't aware of any c/c++ syntax. Put a #undef
directive before the function scope ends.
Upvotes: 1