SwiftMango
SwiftMango

Reputation: 15294

Can I use define directive in a function scope?

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

Answers (4)

Marius Bancila
Marius Bancila

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

poitroae
poitroae

Reputation: 21367

#defines don't keep an own scope as functions do. They are naively replaced by the preprocessor.

#defineing 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

Rahul Tripathi
Rahul Tripathi

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

Related Questions