I was always under the impression that a variable declared in any kind of loop statement is scoped to that statement alone. And a little poking around in similar questions seems to confirm this idea. So I am puzzled by the following excerpt from Stroustrup's A Tour of C++ (§4.2.3 Initializing Containers p. 38):
"The push_back() is useful for input of arbitrary numbers of elements. For example:
Vector read(istream& is) { Vector v; for (double d; is>>d;) // read floating-point values into d v.push_back(d); // add d to v return v; } The input loop is terminated by an end-of-file or a formatting error. Until that happens, each number read is added to the Vector so that at the end, v’s size is the number of elements read. I used a for-statement rather than the more conventional while-statement to keep the scope of d limited to the loop."
This seems to imply that variables declared in the condition of a while statement persist outside the statement body.
forloop statement is in scope for the entire loop body. That being said, "I used afor-statement rather than the more conventionalwhile-statement to keep the scope ofdlimited to the loop" - if you usestd::copy()withstd::istream_iteratorandstd::back_inserter, you can eliminate the loop altogether, eg:std::copy(std::istream_iterator<double>(is), std::istream_iterator<double>(), std::back_inserter(v));