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

Était-ce utile?

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top