Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a compile error in this code?

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

like image 833
Mansuro Avatar asked Mar 29 '26 23:03

Mansuro


2 Answers

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.

like image 96
Matt Fenwick Avatar answered Apr 02 '26 19:04

Matt Fenwick


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.

like image 31
Mat Avatar answered Apr 02 '26 20:04

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!