loop question

Started by
3 comments, last by jpetrie 16 years, 11 months ago
i been reading c++ tutorials and i was just making some small program to try and use what i have learned so far. in it i was using a do while loop. originally i had the do part at the very beginning of the program(before variables were introduced) i kept getting errors pointing to my while statement at the bottom. i was toying around and moved the do after the variables were introduced and no more error and my program ran. i was just wondering if anyone could explain why this happens? thanks hey
Advertisement
Can you post the code? I can think of a number of errors - in no particular order

You could have been missing a semicolon after the while portion of the loop

You could have been referring to a variable in the while condition before declaring it

You could be compiling as C in which case variable declarations are required to be the first thing in any given scope.

Any of these things and more could be problems - post code using
[ source ] [ /source ] tags but without the spaces. You might also include what compiler you are using and the exact text of the error message
Possible, but what also sounds quite likely is that the variables used in the 'while' would fall out of scope if defined within the 'do' block.
If you introduce a value within a do/while loop
the values are only "ALIVE" for a single loop.
Everey time the loop runs are introduced again and again.
Sounds like a scoping issue, but its hard to say without code.

Remember in C++, pairs of braces ({ and }) denote a scope. Any pair of braces does this - including the braces used to block off the bodies of loops.

Any variables declared in one scope cease to exist once execution leaves that scope, and not not visible to an outer scope. For example:

#include <iostream>int main(){ // This brace begins the scope of the main() function.    int a = 10;  while(a > 0)  { // This brace begins a new, inner scope.        int b = a;    // We can safely access variables from an outer scope, such as a:    --a;    // We can also, obviously, access variables of our own scope.    b = 10;    // We can even create inner scopes without using an if, do, while, etc.    // Just a pair of braces is sufficient:    {      int c = a + b;      std::cout << c << "\n";    }  // c goes out of scope and is destroyed here.  } // b goes out of scope and is destroyed here.  // At this point, we cannot access b. It's gone.  //b = 10; If you uncomment this line, you'd get a compiler error.} // a goes "out of scope" and is destroyed here


As the above poster noted, in the case of loops, each iteration of the loop enters, executes, and exits the scope defined by its body. So any variables declared within the loop's body are constructed and destructed every iteration of the loop.

This topic is closed to new replies.

Advertisement