Re: Recursive blocks
Re: Recursive blocks
- Subject: Re: Recursive blocks
- From: Chris Suter <email@hidden>
- Date: Thu, 27 Jan 2011 14:04:20 +1100
Hi Glen,
On Thu, Jan 27, 2011 at 1:45 PM, Glen Low <
email@hidden> wrote:
> I would like to call a block recursively. Since blocks are anonymous, this
> would involve either naming the block or some way of accessing the block
> reference from within the block.
[snip]
> This seems to work well, except that when I run it through the static
> analyzer in Xcode 3.2.5, it complains that the factorial2 variable is
> captured by the block with a garbage value. If I make the block variable
> though, it doesn't complain. Since the block works well enough as-is, should
> I ignore this? If this is not per-spec, how would I get the reference to the
> block from within the block in order to call it recursively?
No, you shouldn't ignore this warning. I can think of a few ways around the issue, but I question why you're doing this in the first place—anybody reading your code will wonder if it's correct and a safe thing to do. Far better would be to simply have a function that does the factorial for you and then if you need to make a block out of it, just call your function. For example:
// gcc -o test test.c -W -Wall
// test ! 5 produces:
// =120
#include <stdio.h>
#include <stdlib.h>
int factorial2 (int n)
{
if (n == 1)
return 1;
else
return n * factorial2(n - 1);
}
typedef int (^ufunc_t)(int);
ufunc_t unary_func (int c)
{
switch (c) {
case '!':
return ^(int x){ return factorial2(x); };
}
return NULL;
}
int main (int argc, const char * argv[])
{
if (argc != 3)
return 1;
ufunc_t ufunc = unary_func (argv[1][0]);
if (!ufunc)
return 2;
printf ("=%u\n", ufunc (atoi (argv[2])));
return 0;
}
Kind regards,
Chris
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden