Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@autorelease Pool and Loops (for, while, do) Syntax

clang allows the following loop syntax:

for (...) @autorelease { ... }

while (...) @autorelease { ... }

do @autorelease { ... } while (...);

I haven't found any documentation on that syntax so far (Apple doesn't use this syntax in their guides, at least no in the guides introducing the @autorelease construct), but is it reasonable to assume that the three statement above are equivalent to the three statements below:

for (...) { @autorelease { ... } }

while (...) { @autorelease { ... } }

do { @autorelease { ... } } while (...);

Since that is what I would expect them to be (going by standard C syntax rules), yet I'm not entirely sure if that's really the case. It could also be some "special syntax", where the autorelease pool is not renewed for every loop iteration.

like image 593
Mecki Avatar asked Dec 02 '22 22:12

Mecki


1 Answers

The reason that the first syntax example works is clear when you consider that any conditional statement can omit the { ... } block, resulting in only the following statement being executed.

For example:

if (something == YES)
    NSLog(@"Something is yes");

is equivalent to

if (something == YES)
{
    NSLog(@"Something is yes");
}

The @autoreleasepool { ... } block is simply the next statement following the conditional.

Personally I use the second syntax as it's less error-prone when making changes, and I find it easier to read. Imagine that when you add a statement between the conditional and the @autoreleasepool { ... } block, the result is considerably different from the original. See this naive example...

int i = 1;
while (i <= 10)
    @autoreleasepool
    {
        NSLog(@"Iteration %d", i);
        ++i;
    }

Will output "Iteration 1" through "Iteration 10". However:

int i = 1;
int total = 0;
while (i <= 10)
    total += i;
    @autoreleasepool
    {
        NSLog(@"Iteration %d", i);
        ++i;
    }

Will actually cause an infinite loop because the ++i statement is never reached as it is syntactically equivalent to:

int i = 1;
int total = 0;
while (i <= 10)
{
    total += i;
}

@autoreleasepool
{
    NSLog(@"Iteration %d", i);
    ++i;
}
like image 112
Steve Wilford Avatar answered Jan 16 '23 04:01

Steve Wilford