Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is happening if code is wrapped in curly braces within a function?

Tags:

objective-c

I'm new to Objective C and have noticed in code I've read that sometimes a block of code will be wrapped in curly braces inside of a function.

What does this do?

For example ...

- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions {    

  // Load config, available via macro CONFIG
  {
    NSString *path = [[NSBundle mainBundle] pathForResource: @"config" ofType: @"plist"];
    NSData *data = [[NSData alloc] initWithContentsOfFile: path];
    self.config = [NSPropertyListSerialization propertyListWithData: data
                                                            options: NSPropertyListImmutable
                                                             format: nil
                                                              error: nil];
    [data release];
  }

  // snip

}
like image 584
Lee Probert Avatar asked Apr 21 '11 09:04

Lee Probert


People also ask

What do curly braces do in HTML?

Note: Curly brackets '{ }' are used to destructure the JavaScript Object properties.

What does curly braces mean in JavaScript?

Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.

Why do we use block of statements with braces?

Braces are used around all statements, even single statements, when they are part of a control structure, such as an or statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

What do brackets do in react?

It's just a way of telling the app to take the value of the variable and put it there, as opposed to a word.


2 Answers

That's called "scope"...

Variables declared inside the braces only exists inside the braces.

Imagine the following:

int main( void )
{
  int my_var = 3;
  {
     int my_var = 5;
     printf( "my_var=%d\n", my_var );
  }

  printf( "my_var=%d\n", my_var );

  exit( 0 );
}

This will print:

my_var=5
my_var=3
like image 160
Macmade Avatar answered Oct 17 '22 09:10

Macmade


It's just a way of limiting the scope of the variables declared in the block. In your example path and data will not be visible outside of the curly braces.

like image 37
Tom Jefferys Avatar answered Oct 17 '22 09:10

Tom Jefferys