Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Assigning blocks in an if
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Assigning blocks in an if



Hi all,

The section "Patterns to Avoid" of the Blocks Programming Topics Guide
warns against the following pattern:
http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/Blocks/Articles/bxUsing.html#//apple_ref/doc/uid/TP40007502-CH5-SW2


void dontDoThisEither() {
    void (^block)(void);

    int i = random():
    if (i > 1000) {
        block = ^{ printf("got i at: %d\n", i); };
        // WRONG: The block literal scope is the "then" clause
    }
    // ...
}


But I was curious about whether the following was legal, since the
lack of curly braces around the if statement's then-clause means no
new scope is introduced:

void howAboutThis() {
    void (^block)(void) = nil;

    if (someCondition)
      block = ^{ printf("Hello\n"); }

    // ...

    [foo doSomethingWithBlock:block];
}

My understanding is that the compiler should keep the block live on
the stack until the very end of the function, whereas in the
documented example the compiler is free to reuse the block's slot on
the stack as soon as control has exited the if block's bracketed
then-clause.

--Kyle Sluder
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.