Sign in to follow this  

loop question

Recommended Posts

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

Share this post

Link to post
Share on other sites
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

Share this post

Link to post
Share on other sites
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:

// 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.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this