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

7

9

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?

Resist answered 30/9, 2011 at 15:24 Comment(1)
This is a technique, mostly applied in the C language, for creating local temporary values after the first statement. When execution exits the ending curly brace, all variable created within that scope disappear.Erick
M
13

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.

Makowski answered 30/9, 2011 at 15:27 Comment(2)
That makes sense, but what's confusing me is I thought that would have to be inside a function. If you can just place braces inside a function, I can't see why you would ever have to use a nested function -- Or am I in left field somewhere?Resist
A function has it's own scope, but it's possible to have scope within a function also. This can be very useful, for example C++ objects have destructors and these can be used to free resources at a paricular point when the object goes out of scope. You might want to do this mid function.Principally
L
6

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
}
Lunseth answered 30/9, 2011 at 15:29 Comment(0)
P
4

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

Pustulant answered 30/9, 2011 at 15:27 Comment(0)
P
4

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.

Principally answered 30/9, 2011 at 15:27 Comment(0)
G
3

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

Gymno answered 30/9, 2011 at 15:27 Comment(0)
I
3

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.

Implant answered 30/9, 2011 at 17:13 Comment(0)
E
1

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

Emelda answered 30/9, 2011 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.