What is the possible use for “#define for if (false) {} else for”?

后端 未结 4 829
暖寄归人
暖寄归人 2020-11-29 05:28

In another question, I just spotted this little pearl of C wisdom:

#define for if (false) {} else for

which caused MSVC to

4条回答
  •  一向
    一向 (楼主)
    2020-11-29 06:13

    The effect was already described.

    The reason to have it is to port C++ code to MSVC. Or it is also very helpfull if you want your C++ code platformindependent. For example, you developed it on Linux/MacOSX and now want to compile it in MSVC.

    And it is also very usefull for C++ itself. For example:

    for(std::set::iterator i = myset.begin(); i != myset.end(); ++i) {
        // ...
    }
    
    for(int i = 0; i < N; ++i) {
        // ...
    }
    

    I have seen MSVC code which worked around this by doing either:

    for(std::set::iterator i1 = myset.begin(); i1 != myset.end(); ++i1) {
        // ...
    }
    
    for(int i2 = 0; i2 < N; ++i2) {
        // ...
    }
    

    Or:

    {for(std::set::iterator i = myset.begin(); i != myset.end(); ++i) {
        // ...
    }}
    
    {for(int i = 0; i < N; ++i) {
        // ...
    }}
    

    In both cases (imo) not that nice. And this #define is a small hack to make MSVC behave more standard.

提交回复
热议问题