Gary
Gary

Reputation: 13912

Can Someone Explain This Snippet (Why Are These Braces Here)?

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

Answers (7)

mimoklepes
mimoklepes

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

sjngm
sjngm

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

Law Metzler
Law Metzler

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

Matt
Matt

Reputation: 75307

The braces define a scope level. Outside of the braces, y will not be available.

Upvotes: 3

Benj
Benj

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

Steve Wellens
Steve Wellens

Reputation: 20620

It's defining scope. The variable Y is not accessible outside the braces.

Upvotes: 4

tafoo85
tafoo85

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

Related Questions