Why does Visual Studio Community 2022 compile my c++ code?

Viewed 98

In my program, I have the following code, and somehow it compiles, but it shouldn't.

#include <list>
#include <iostream>

int main(int argc, char* argv[])
{
    std::list<int> collection = { 1, 2, 3, 4, 5, 6 };

    for each (auto i in collection)
    {
        std::cout << i;
    }

    return 0;
}

I got this code from auto-completion:

for each (auto item in collection)

I use the following command in the Developer Powershell to compile my code:

cl /EHsc /std:c++17 .\programm.cpp

Please help me. I have no idea why this happens, and when I am trying to search for it on the Internet, all I find are problems where it doesn't compile.

1 Answers

A for each loop is a Microsoft-specific extension to the C++ language:

for each, in

Iterates through an array or collection. This non-standard keyword is available in both C++/CLI and native C++ projects. However, its use isn't recommended. Consider using a standard Range-based for Statement (C++) instead.

...

Syntax

for each ( type identifier in expression ) {
  statements
}

That is why the code compiles in Visual Studio. It will not compile in any other C++ compiler.

Related