I can’t understand what the problem is. This code just does not compile:
int main (int argc, char * argv [])
{
int arr [] = {1,2,3,4,5,6,7};
for each (int var in arr)
{
}
system ("pause");
}
Compilation error: expected a {
.
What is he missing here?
Answer 1, authority 100%
Apparently this is non-standard syntax for each, in
, implemented in due time in VC++ and VC++ / CLI. However, the C++ standard has an alternative syntax, which should be used:
for (auto const & amp; int: arr)
{
}
Answer 2, authority 100%
in C++ for each
is not a language construct but a function from the STL
standard library that should be used as follows in your example:
# include & lt; iostream & gt;
#include & lt; algorithm & gt;
int main (int argc, char * argv [])
{
int arr [] = {1,2,3,4,5,6,7};
std :: for_each (arr, arr + sizeof (arr) / sizeof (arr [0]), [] (int el)
{
std :: cout & lt; & lt; el & lt; & lt; '';
});
system ("pause");
return 0;
}
Answer 3, authority 33%
Your compiler may not support this option. And he does the right thing, in general, because it is a complete non-standard.
The standard notation (since C++ 11) is as follows:
int main (int argc, char * argv [])
{
int arr [] = {1,2,3,4,5,6,7};
for (int var: arr)
{
}
}