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?
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.
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
}
It's defining scope. The variable Y is not accessible outside the braces.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With