Redefine(#define) reserved c++ key word

前端 未结 4 1052
南方客
南方客 2021-01-26 12:20

Is it possible to redefine a c++ keyword using #define?

#ifdef int
#undef int 
#define int 2
#endif
int main(){
    //Do something with int
}

I

相关标签:
4条回答
  • 2021-01-26 12:31

    You can, but you shouldn't.

    In your examples, int doesn't get redefined, since it's wrapped in #ifdef int. That means "only do this if there's already a preprocessor macro called int", and there isn't.

    If you just wrote #define int 2, then all occurrences of int would be replaced by 2; but then your code wouldn't compile since 2 main() {cout<<2;} is nonsense.

    #undef will not remove a keyword from the language; it only removes preprocessor macros previously defined using #define.

    0 讨论(0)
  • 2021-01-26 12:38

    Technically it works but it probably won't do you much good. If you want to use the standard C++ library you are not allowed define any of the keywords or any of a set of other names according to 17.6.4.3.1 [macro.names] paragraph 2:

    A translation unit shall not #define or #undef names lexically identical to keywords, to the identifiers listed in Table 3, or to the attribute-tokens described in 7.6.

    0 讨论(0)
  • 2021-01-26 12:46

    Is it possible? Yes. Is it good style? Absolutely not.

    The preprocessor is not aware of C/C++ keywords, it only knows about preprocessor tokens and just does strict text replacement.

    Your example is resulting in an error because you're #undefing it. Once you undefine it, it reverts to its previous behavior.

    The only valid use I know of for doing something like this is to work around a bug in an old compiler, and that compiler is no longer relevant these days.

    0 讨论(0)
  • 2021-01-26 12:49

    If you're don't use the standard libraries you're allowed to do so. In fact the preprocessor shouldn't distinguish between reserved and non-reserved words.

    However that's probably not why you run into problems. First of all your examples don't do what you probably think. The fault is that int is normally not a preprocessor defined macro. The #ifdef int directive will therefore skip the following lines up to the terminating #endif.

    What this means is that your second example expands to:

    // stuff from iostream and possibly other headers 
    
    int main(){
        cout<<int;
    }
    

    the fault is that cout<<int; simply isn't allowed.

    0 讨论(0)
提交回复
热议问题