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?
Think of an if statement as:
if this then that else this other thing
The
{... block = ...}is in the then that part of theifstatement. That is, it is *a sub-scope of the scope of thedontDoThisEither()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
ifstatement.I.e. Consider:
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).