Skip to content

Instantly share code, notes, and snippets.

@andrep
Created April 2, 2011 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrep/899755 to your computer and use it in GitHub Desktop.
Save andrep/899755 to your computer and use it in GitHub Desktop.
A gotcha when using Apple's blocks in (Objective-)C: what do you think this prints to the screen?
#include <Block.h>
#include <stdlib.h>
#include <stdio.h>
/* see <http://stackoverflow.com/questions/938429/scope-of-python-lambda-
functions-and-their-parameters> for for the inspiration for this */
/* block taking no parameters and returning void */
typedef void (^void_block_t)();
int main()
{
char* strings[3] = { "do", "re", "mi" };
void_block_t print_funcs[3];
int i;
for(i = 0; i < 3; i++)
{
char* s = strings[i];
/* note that the reason this works is not directly
* because of the block copy: it works because the
* Block_copy will perform a copy of s's current
* value when it copies the block, instead of simply
* referencing s. */
print_funcs[i] = Block_copy(^{ printf("%s\n", s); });
}
/* prints "mi, mi, mi" */
for(i = 0; i < 3; i++)
{
print_funcs[i]();
/* and don't forget to do this. yay memory management! */
Block_release(print_funcs[i]);
}
return 0;
}
#include <stdlib.h>
#include <stdio.h>
/* see <http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters> for for the inspiration for this */
/* block taking no parameters and returning void */
typedef void (^void_block_t)();
int main()
{
char* strings[3] = { "do", "re", "mi" };
void_block_t print_funcs[3];
int i;
for(i = 0; i < 3; i++)
{
char* s = strings[i];
print_funcs[i] = ^{ printf("%s\n", s); };
}
/* prints "mi, mi, mi" */
for(i = 0; i < 3; i++)
{
print_funcs[i]();
}
return 0;
}
module HaskellClosureTest where
strings = ["do", "re", "mi"]
main = do
let printFunctions = map (\s -> putStrLn s) strings
-- prints "do, re, mi"
mapM_ id printFunctions
# stolen directly from <http://stackoverflow.com/q/938429>
def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#what do i print?
@andrep
Copy link
Author

andrep commented Apr 3, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment