Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
Gary Avatar asked Sep 30 '11 15:09

Gary


4 Answers

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.

like image 82
tafoo85 Avatar answered Oct 13 '22 16:10

tafoo85


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
}
like image 25
sjngm Avatar answered Oct 13 '22 15:10

sjngm


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

like image 4
Steve Wellens Avatar answered Oct 13 '22 15:10

Steve Wellens


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.

like image 4
Benj Avatar answered Oct 13 '22 16:10

Benj