Scrungepipes
Scrungepipes

Reputation: 37581

Don't understand example given of block scope

In the Apple block documentation is an example of code not to write:

void dontDoThisEither() {
  void (^block) (void);
  int i = random();
  if (i > 1000) {
    block = ^{printf("got i at: %d\n", i); };
  }
  // ...
}

The comments for the code say the block literal scope is the "then" clause. I don't understand what they mean by that, there is no then clause, which is presumably why they have put it in quotes. But why have they put it in quotes and what is the relationship to the block's scope?

Upvotes: 2

Views: 142

Answers (1)

bbum
bbum

Reputation: 162712

Think of an if statement as: if this then that else this other thing

The {... block = ...} is in the then that part of the if statement. That is, it is *a sub-scope of the scope of the dontDoThisEither() function.

Because blocks are created on the stack and are only valid within the scope of their declaration, that means that the block assignment in that example is only valid within the then that scope of the if statement.

I.e. Consider:

void dontDoThisEither() {
  void (^block) (void);
  int i = random();
  if (i > 1000) {
    block = ^{printf("got i at: %d\n", i); };
  }  else {
    block = ^{printf("your number is weak and small. ignored.\n");};
  }
  block();
}

At the time block(); is executed the block that it is pointing to is in a scope that is no longer valid and the behavior will be undefined (and likely crashy in a real world example).

Upvotes: 2

Related Questions