What happens if the code is wrapped in curly braces inside a function?

I am new to Objective-C and noticed in the code that I read that sometimes a block of code will be wrapped in curly braces inside a function.

What does it do?

For instance...

- (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

}
+5
source share
2 answers

This is just a way to limit the amount of variables declared in a block. In your example, the path and data will not be visible outside the curly braces.

+5
source

This is called "scope" ...

Variables declared inside curly braces exist only inside curly 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
+10
source

All Articles