0

I came across below example in w3schools, while learning about javascript closures. I was wondering if this could be achieved in C programming, since we have similar function pointers in C. However, I was not able to completely achieve this with simple pointers to function implementation. Can someone please give it a try? Redirect me if it has already been asked.

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();

// the counter is now 3
goodbytes
  • 428
  • 3
  • 8
  • 21
  • Tried returning a function from another, but I coundn't access the counter from outside of it. Also, I couldn't define a function inside another since well, it's C. – goodbytes Feb 17 '16 at 07:19
  • 1
    Then please edit your question and show that, even it if is wrong. – Jabberwocky Feb 17 '16 at 07:20
  • 1
    @goodbytes Include your attempts in the question, not in the comments, since _the question has to include your attempts_. – Sebastian Simon Feb 17 '16 at 07:20
  • @MichaelWalz: I don't really know what you'll learn from the attempt on a question that asks "is this even possible?" (especially when the answer is, in absence of someone smarter than me, a rather resounding thud of a "nope"). – Amadan Feb 17 '16 at 07:23
  • @Amadan question includes this : " I was not able to completely achieve this....", that suggested that the OP has tried something. – Jabberwocky Feb 17 '16 at 07:29

1 Answers1

3

In a word, not really. A closure is, effectively, a structure that consists of a function pointer, if you will, and the captured state (the variables that are closed over). You cannot capture state in C. You could fake a closure by explicitly defining a structure to hold state, and explicitly passing this structure in to the function; but then a) it gets messy, and b) what's the point of not passing counter when you need to pass a struct with counter?

Your specific code could be done by explicitly defining counter as a static variable; but it is not generalisable to what closure really is.

EDIT: Apparently there is a mechanism to pass the structure for you: FFCALL. It is still ugly. Anyway, moving to close as duplicate.

Amadan
  • 191,408
  • 23
  • 240
  • 301