Ehsan Amini
Ehsan Amini

Reputation: 169

scope of variables in loops

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.

Upvotes: 1

Views: 843

Answers (2)

torkleyy
torkleyy

Reputation: 1217

[..] that variables declared in the condition of a while statement [..]

That's not possible.

Using a for statement allows to declare a variable like this

for(int a = 0; a < 5; a++) {
    // Use a
}
// a is not visible anymore

If you use a while loop, it is visible

int a = 0;
while(a < 5) {
    // Use a
    a++;
}
// a still visible

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Let's examine that loop:

for (double d; is>>d;) // read floating-point values into d
    v.push_back(d); // add d to v

Here we have:

  • a declaration of d
  • a loop condition
  • an empty "do on each iteration" expression

And, yes, d is limited in scope to the for loop.

Now try writing a while loop to do the same job, keeping d limited in scope. You won't be able to, because there's no place to put a declaration in the preamble of a while. Only for has that feature. A while only has a condition.

That doesn't mean the scoping rules are different for while; it only means that it is not possible to write this code using while. There aren't any "variables declared in the condition of a while statement".

Upvotes: 4

Related Questions