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

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top