This fix the error in older versions of Visual C ++ (v6.0 and earlier). In the past, Visual C ++ violated the scope rules of variables declared inside for statements:
// This compiles in old versions of Visual C++, but it is in fact INVALID C++ for(int i = 0; ...) { ... } for(i = 0; ...) { }
In other words, Visual C ++ provides i scope as if it were declared outside the loop, and allows you to continue using it after the loop finishes. This leads to the creation of code, such as the above snippet. In more standards-compliant compilers, i no longer in the scope of the second for loop, so the compiler throws an error about i as undefined.
To fix this, some people used this macro (or very similar, equivalent macros):
#define for if(0) {} else for
This changes the for loop to this:
if(0) { } else for(int i = 0; ...) { ... }
This puts the for loop in an extra layer of visibility, so that any variables declared in the for loop will subsequently be out of scope, regardless of the Visual C ++ error. This ensures that the same code compiles correctly both in Visual C ++ and in standards compatible with compilers, and that the wrong code does not compile correctly.
Also note that if a macro was defined as follows:
// DO NOT USE
Then, although this will have the same effect for some simple code, it may lead to incorrect compilation of the following code:
if(foo) for(...) { ... } else doSomething();
Because if you expand the macro, you get the following:
if(foo) if(1) for(...) { ... } else doSomething();
And else now matches the wrong if ! Thus, clever use of if(0) {} else instead of if(1) fixes this problem.
As a final note, #define for if(0) {} else for does not cause infinite recursion, since the preprocessor will not recursively replace the macro that you are currently defining. In this case, he will perform only one replacement.