Dispatch_apply() question


#1

In chapter 22, the following is given as an example of using dispatch_apply():

dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(self.count, dispatchQueue, ^(size_t index) { results[index] = Work (numbers, index); });

In Xcode 4.3.2, the LLVM 3.1 compiler doesn’t allow this because of the following error:“Cannot refer to declaration with an array type inside block”.

Does this work with GCC or a previous version of LLVM?

I found this on the dev forums about it
https://devforums.apple.com/message/540440#540440

Thanks,
Matthew


#2

Interesting. The original code works in LLVM because the results array is a global, so it’s happily accessible inside the block. Moving the results array declaration inside of main yields the error you found. That struct-wrapping trick is one way to work around the problem.

Good catch. Now to figure out how to edit the text and explain it :slight_smile:


#3

And an addendum (Jeremy Sherman got me to read the forum post a little more closely) - if you demote the array to a pointer, it’s happy again. So like

int resultsArray[42]; int *results = resultsArray; ... happily use results[blah] in a block


#4

And more. Were learning together! It looks like this will just capture the pointer reference, not the actual contents (I need to experiment to verify that), but glancing at places in the Clang source that Jeremy’s pointed me to, it looks like just the reference is captured, not the array, so this would be like returning a dangling reference.