Mansuro
Mansuro

Reputation: 4627

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

Upvotes: 3

Views: 161

Answers (4)

sidyll
sidyll

Reputation: 59297

This code has some problems:

  • You declare lessThanTest as an uninitialized function pointer
  • You can't assign something to it later under global scope
  • You're using LessThan before declaring it.

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143219

Well, no, if lessThan is global, it shouldn't produce compile error, though you can hardly tell by this fragment what is meant to be where. lessThanTest=&LessThan; is definitely from some local scope, for instance.

Upvotes: 0

Mat
Mat

Reputation: 206831

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.

Upvotes: 1

Matt Fenwick
Matt Fenwick

Reputation: 49105

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.

Upvotes: 2

Related Questions