When is storing a reference to a function in a variable actually useful? I don't understand why it's need, maybe I'm just overlooking something, I just really don't see when that would be useful. Anyone who can explain this, I will greatly appreciate your explanation.

Reply to this note

Please Login to reply.

Discussion

In C, threading uses pointer to function

Sometimes you want to pass the function to a new scope to execute and the closure around that function is available where it might not be

Sounds like callback, completely forgot about this one

Couldn't you just call the function like you normally would though? I'm new to this and if I'm dumb for this I'm ok with that lol.

If the closure does not exist inside the scope you’d like to call it on then yes, you need to pass it as a variable depending on language of course

In the case of a callback, only at at runtime will you know which function to call

So for example you have a function to add money to a bank account and a function to subtract money from a bank account and you don't know which the user will choose to do when they use the application?

Yeah it's stuff like that. Let's say you are a caller of a function that does a withdrawal based on the result of a validation. The caller wants the function to use withdrawal method A, and provides the method. There is more than one withdrawal method, so that's how the caller is telling it which one to use