Reputation: 13912
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?
Upvotes: 9
Views: 444
Reputation: 31
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.
Upvotes: 3
Reputation: 12861
It's a matter of scoping variables, e.g.:
void f5()
{
int x = 1;
{
int y = 3;
y = y + x; // works
x = x + y; // works
}
y = y + x; // fails
x = x + y; // fails
}
Upvotes: 6
Reputation: 1235
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
Upvotes: 1
Reputation: 75307
The braces define a scope level. Outside of the braces, y
will not be available.
Upvotes: 3
Reputation: 32398
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.
Upvotes: 4
Reputation: 20620
It's defining scope. The variable Y is not accessible outside the braces.
Upvotes: 4
Reputation: 879
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.
Upvotes: 13