Do I need to #undef a local #define? Is there such a thing as a local define?

后端 未结 6 1068
刺人心
刺人心 2021-02-05 12:45

Sometimes to make things easier to write and read, I write some local #define macros within functions (for example, #define O_REAL Ogre::Real).

6条回答
  •  花落未央
    2021-02-05 12:59

    Unfortunately, #defines do not respect scoping rules. #defines that are not #undef'd will affect all code after them. Additionally, if code before you defines the same macro name, you'll have problems. In C++ you can usually avoid needing to use such local macros with local typedefs and references. For example, you could do:

    void foo() {
        typedef Ogre::Real O_REAL;
        // ... 
    }
    

    This will respect scoping rules. For variables you can use references:

    void foo() {
        int &BAR = Foo::quux::baz::static_bar;
        // ...
    }
    

提交回复
热议问题