for each loop with if else statement
-
Just out of curiosity: What is the reason, that the following code doesn't compile under Visual Studio:
int main(array ^args)
{
array^ l = {1,2,3};for each (int a in l)
if (a % 2 == 1)
Console::WriteLine ("even");
else
Console::WriteLine ("odd");return 0;
}
This results in the error "else without if". One needs to use a compound statements around the if-else-statement. Using a standard for-loop this works as expected, of course:
int main(array ^args)
{
array^ l = {1,2,3};for (int i = 0; i < l->Length; ++i)
if (l[i] % 2 == 1)
Console::WriteLine ("even");
else
Console::WriteLine ("odd");return 0;
}
-
Just out of curiosity: What is the reason, that the following code doesn't compile under Visual Studio:
int main(array ^args)
{
array^ l = {1,2,3};for each (int a in l)
if (a % 2 == 1)
Console::WriteLine ("even");
else
Console::WriteLine ("odd");return 0;
}
This results in the error "else without if". One needs to use a compound statements around the if-else-statement. Using a standard for-loop this works as expected, of course:
int main(array ^args)
{
array^ l = {1,2,3};for (int i = 0; i < l->Length; ++i)
if (l[i] % 2 == 1)
Console::WriteLine ("even");
else
Console::WriteLine ("odd");return 0;
}
-
Dunno, but odd/even appear to be transposed (or the if(%) incorrect). %2 == 0 would be even?
Yeah, right, typo. But this is not the point of the question!