"for each" statement in C++/CLI
c++-cli, syntax
Solution
I can't find any official documentation on it, but I can confirm the behavior you're seeing. It simply appears that the compiler is overly aggressive about finding the single statement following the `for each`, to the point of splitting the `else` from the `if`. It compiles it as if you had written the following, which is clearly incorrect.
array<int> ^ints = gcnew array<int>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for each(int i in ints)
{
if(i % 2 == 0)
Debug::WriteLine("Even\n");
}
else
Debug::WriteLine("Odd\n");
This is obviously different to how a regular C++ `for` loop behaves, so you may wish to file a bug at http://connect.microsoft.com.
Problem
``` array<int> ^ints = gcnew array<int>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for each(int i in ints) if(i % 2 == 0) Debug::WriteLine("Even\n"); else Debug::WriteLine("Odd\n"); ``` Why does the above fail to compile? It works fine if I use a `for(int i; ...)` or if I enclose the `if-else` within braces. I know that the manual clearly indicates that braces are required, but I want to know why this departure from expected behaviour?