有人可以解释一下这个片段(为什么这些大括号在这里)?
我对这个过于简单化的问题表示歉意,但我似乎无法弄清楚我正在阅读的书中的这个示例:
void f5()
{
int x;
{
int y;
}
}
int y
周围的大括号是什么?您可以将牙套放在您想要的任何地方吗?如果是这样,您何时以及为何这样做,或者这只是书中的一个错误?
I apologize for this overly simplistic question, but I can't seem to figure out this example in the book I'm reading:
void f5()
{
int x;
{
int y;
}
}
What are the braces surrounding int y
for? Can you put braces wherever you want? If so, when and why would you do so or is this just an error in the book?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
大括号表示范围,变量 x 在内大括号的范围内可见,但 y 在其大括号范围之外不可见。
The braces denote scope, the variable x will be visible in the scope of the inner brace but y will not be visible outside of it's brace scope.
大括号定义范围级别。在大括号之外,
y
将不可用。The braces define a scope level. Outside of the braces,
y
will not be available.在作用域出口处,内部对象被破坏。例如,您可以将关键部分括在大括号中并在其中构造一个锁定对象。然后您不必担心忘记解锁它 - 退出作用域时会自动调用析构函数 - 无论是正常情况还是由于异常。
At the scope exit the inner objects are destructed. You can, for example, enclose a critical section in braces and construct a lock object there. Then you don't have to worry about forgetting to unlock it - the destructor is called automatically when exitting the scope - either normally or because of an exception.
这看起来像是一个错误(不知道上下文)
这样做,您已将值 y 装箱在这些大括号内,因此在大括号之外不可用。
当然,如果他们试图解释范围,那可能是有效的代码
That looks like an error (not knowing the context)
Doing that you have boxed the value y inside those braces, and as such is NOT available outside it.
Of course, if they are trying to explain scope, that could be a valid code
像这样的大括号表明大括号内的代码现在处于不同的范围内。如果您尝试访问大括号之外的 y,您将收到错误。
Braces like that indicate that the code inside the braces is now in a different scope. If you tried to access y outside of the braces, you would receive an error.
这是一个范围变量的问题,例如:
It's a matter of scoping variables, e.g.:
它正在定义范围。变量 Y 在大括号之外不可访问。
It's defining scope. The variable Y is not accessible outside the braces.