xmllmx
xmllmx

Reputation: 42371

Will C++17 support the simpler Range-based For Loop?

Since C++11, we can write:

vector<int> v{1, 2, 3, 4};
for (auto x : v)
{
    cout << x << endl;
}

According to Essentials of Modern C++ Style, the following code will soon be also legal in C++:

vector<int> v{1, 2, 3, 4};
for (x : v)
{
    cout << x << endl;
}

Will this feature be available in C++17 or C++20?

Upvotes: 29

Views: 4697

Answers (3)

Qwertiy
Qwertiy

Reputation: 21400

Update

GCC 5.1 allows this syntax with -std=c++1z.
This is not allowed anymore since GCC 6.1.

So this answer doesn't seem to be correct.

Ideone compiler successfully compiles such code under C++ 14:

http://ideone.com/KONqTW

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v {1, 2, 3, 4};

    for (x : v)
        cout << x << endl;

    return 0;
}

Upvotes: 1

T.C.
T.C.

Reputation: 137315

No. This was killed by the committee more than two years ago, mostly because of concerns about potential confusion caused by shadowing:

std::vector<int> v = { 1, 2, 3, 4 };
int x = 0; 
for(x : v) {} // this declares a new x, and doesn't use x from the line above
assert(x == 0); // holds

The objections came up so late in the process that both Clang and GCC had already implemented the feature by the time it got rejected by the full committee. The implementations were eventually backed out: Clang GCC

Upvotes: 60

user743382
user743382

Reputation:

This is still an open issue. There was a proposal, linked there, to add this to C++17. That proposal was rejected. Whether a new proposal will be accepted depends on the proposal, so it's too soon to say whether C++20 might have it.

Upvotes: 4

Related Questions