What will this “block” code print?

This sample is from Apple’s document, “Blocks Programming Topics

void dontDoThis( void ) 
    void (^blockArray[3])(void);  // an array of 3 block references
    for (int i = 0; i < 3; ++i) {
        blockArray[i] = ^{ printf("hello, %d\n", i); };
        // WRONG: The block literal scope is the "for" loop
    for (int j = 0; j < 3; ++j) {
        blockArray[j](); // What will it print?

What will the code above print?
The “i” is out of scope when the loop with j is processed. Then… will it crash? Will the compiler complain about it? Actually the compiler doesn’t say anything.

The result is :

hello, 2
hello, 2
hello, 2

So, when the array of blocks is constructed, the i in the block is still alive as a variable. So, the last i, which is 2, is there no matter what element in blockArray is.
So, the blockArray[j]() prints “hello, 2”.

However, to me it is still strange. When the “i” is out of its scope, it should crash or complain somehow.


One response to this post.

  1. […] What will this “block” code print?li> here is one for the function/function object. This is an example from the side which shows how the function object looks like in JavaScript. […]


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: