Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with blocks?

In an interview I recently attented I was asked to predict the output of a code segment. Even if I got it right, I was not able to explain how got it. This is the code segment.

int num =2;
int (^ myblock)(void)=^{
    return num*5;
};

NSLog(@"my block  call 1  %d",myblock());
num = 5;
NSLog(@"my block  call 2  %d",myblock());

Can anybody explain why the answer is 10 both times.? Thanks

like image 516
user3292590 Avatar asked Feb 20 '26 05:02

user3292590


1 Answers

The num variable gets copied within the block if not marked with __block. This means that the external scope num and the inner num are actually kept at different addresses in memory and changing one doesn't affect the other. To force the compiler to use the same address, mark the variable with __block

like image 65
Rad'Val Avatar answered Feb 22 '26 18:02

Rad'Val