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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With