I was trying to understand the difference between closures and function pointers, and I came across this answer in SO
What I don't understand is this code
BOOL (*lessThanTest)(int);
int lessThan = 100;
lessThanTest = &LessThan;
BOOL LessThan(int i) {
return i < lessThan; // compile error - lessThan is not in scope
}
Why there is a compile error consideringn that lessThan is a global variable, it can be accessed from within LessThan function, did I miss something?
EDIT
This is not my code, it's taken from an answer in SO Function pointers, Closures, and Lambda
Closures take all the variables in their lexical scope along for the ride, possibly extending their lifetimes. Function pointers don't -- if the variables referenced inside their code disappear, they're hosed.
The code example you've given is a little bit confusing. I believe that it's meant to be inside of a function, meaning that lessThan is a local variable. If that scope is exited, but the function pointer still exists, then its code would have a reference to a non-existent variable -- lessThan.
You missed a paragraph in that answer:
But, now I have to pass the 2 arguments when I evaluate it. If I wished to pass this function pointer to another function where lessThan was not in scope, I would either have to manually keep it alive by passing it to each function in the chain, or by promoting it to a global.
In what you posted, int lessThan is not meant at global scope, it should be assumed to be in a function somewhere.
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