Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 902
xmllmx Avatar asked Dec 23 '16 10:12

xmllmx


People also ask

Does C have range-based for loops?

Range-based for loop in C++ It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

When would you use a range-based loop?

Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .

Are range-based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).


1 Answers

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

like image 103
T.C. Avatar answered Sep 23 '22 19:09

T.C.