aneuryzm
aneuryzm

Reputation: 64864

What does this syntax with brackets only mean?

I was surprised to see in a objective-c project, the following line codes

- (void)methodName
{
    ... some code...

    {
        ... some code
    }

    {
        ... some code
    }

}

What does the inner brackets stand for ? They seems not be preceded by any statement. thanks

Upvotes: 3

Views: 278

Answers (4)

Joel Fischer
Joel Fischer

Reputation: 6597

They create a block scope. Declared variables inside those blocks will not be available outside the blocks.

Upvotes: 3

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

The brackets create a new scope. Variables defined within the scope will not persist after the end of the scope. I personally use this to separate out bits of logic to make things easier to read.

Example 1

This example demonstrates the lack of access to variables instantiated inside of a more narrowly defined scope.

-(void)blockTestA {
    int j = 25;

    {
        int k = 5;

        // You can access both variables 'j' and 'k' inside this block.
    }

    // You can only access the variable 'j' here.
}

Example 2

This example demonstrates how creating a new block scope allows us to have different variables with the same name. You can read more about scope here.

-(void)blockTestB {
    int j = 25;

    {
        int j = 5;
        NSLog(@"j inside block is: %i", j); // Prints '5'
    }

    NSLog(@"j outside of block is: %i", j); // Prints '25'
}

Upvotes: 5

Prasad G
Prasad G

Reputation: 6718

- (void)methodName
{
    ... some code...

    {
      int i;//the scope of i is within this block only
        ... some code
    }

    {
       int i;//the scope of i is within this block only
       ... some code
    }

}

I think it will be helpful to you.

Upvotes: 2

Mike Pelley
Mike Pelley

Reputation: 3126

The inner brackets limit the scope of variables declared inside of them.

Upvotes: 3

Related Questions