C Blocks as Arguments

I don’t know the details, but based off the little I’ve read online, Apple added the ability to point to C blocks. This means that you can do interesting stuff like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
 
void repeat(int num, void(^block)()){
	for (int i = 0; i < num; i++){
	  printf("--");
	  block();
	}
}
 
int main() {
 
	repeat(10, ^{
		static int i = 0;
		i++;
		printf("%d\n", i);
	});
 
	return 0;
}

This will output:

--1
--2
--3
--4
--5
--6
--7
--8
--9
--10

It’s common in jQuery to do things like:

thing.click(function(){
  alert("I was clicked");
});

Kind of interesting that you can do it in C too…

Based on googling, this works in osx 10.6 and with a little tweak of the compiler settings 10.5.

As a side note, this is doable pretty much across the board with function pointers – you just don’t have anonymous functions so you have to define a function and then pass it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
 
void runTen(void (*func)()){
	for(int i = 0; i < 10; i++)
		func();
}
void count(){
	static int i = 0;
	printf("--%d\n", ++i);	
}
 
int main(){
       // no need for &
	runTen(count);
	return 0;
}

I could still see using the block technique in certain scenarios – especially with some of the interesting things going on in Block.h like Block_copy() etc…

For more info check out this great explanation:

http://thirdcog.eu/pwcblocks/



 
 
 

Leave a Reply

Spam protection by WP Captcha-Free