Search code examples
c++functioncode-snippetscurly-braces

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?


Solution

  • 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.