Question

I was reading this book and it said : Variables declared in a scope aren't visible outside it.

It also said : Scopes are declared by 2 curly braces - like a block of code.

So, if I had a situation like this :

for(_statement1_)
{
  int var;
  /*code*/
}
cout << var << " number of rockets left.\n";

Would the value printed be the same as the value of the var declared in the loop?

Thank you

Was it helpful?

Solution

As your book says, the variable is scoped inside the loop's block, and isn't visible outside it.

Your code won't compile unless there is a different variable var outside the loop's scope. If there is, then the final statement would use that, not the one in the loop which is now out of scope.

OTHER TIPS

No, you can not use that variable outside the loop. var is visible only inside the loop.

It will be a compiler error since the scope of var limited inside for loop only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top