I can not understand what the problem is. This code is simply not compiled:

int main(int argc, char * argv[]) { int arr[] = { 1,2,3,4,5,6,7 }; for each (int var in arr) { } system("pause"); } 

Compile error: expected a { .

What does he lack here?

    3 answers 3

    Apparently this is a nonstandard syntax for each, in , implemented at one time in VC ++ and VC ++ / CLI. However, the standard C ++ got an alternative syntax, which should be used:

     for(auto const & int: arr) { } 
    • just figured it out. thank. It is strange that the author, who described the built-in for each, did not indicate the standard. - raviga
    • @DimaKhodan Maybe the article or version of the compiler was old? This syntax appeared before the release of the new standard. - VTT
    • The fact of the matter is that March 18th year. - raviga

    in c ++ for each is not a language construct, but a function from the standard STL library, which should be used as follows in your example:

     #include <iostream> #include <algorithm> 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 << el << ' '; }); system("pause"); return 0; } 
    • I know about the for_each algorithm, but the point here is that it is a loop. I read an article about the foric cycle, and wanted to try a couple of examples, but as an author, it simply does not work. - raviga
    • @DimaKhodan what you read there is likely this std::for_each . - ampawd
    • do you think I can not distinguish the built-in odds from the algorithm? - raviga
    • @DimaKhodan I do not know, but in your example the syntax error is ampawd
    • one
      @DimaKhodan if your compiler supports the 11th standard - use the range based loop ie: for (auto el: arr) { ... } - ampawd

    Your compiler may not support the above version. And rightly so, in general, because it is a complete non-standard.

    The standard entry variant (starting with C ++ 11) is:

     int main(int argc, char * argv[]) { int arr[] = { 1,2,3,4,5,6,7 }; for (int var : arr) { } }