Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Closure (computer programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====Nested function and function pointer (C)==== With a [[GNU Compiler Collection]] (GCC) extension, a nested function<ref>{{cite web |url = https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html |title = Nested functions}}</ref> can be used and a function pointer can emulate closures, provided the function does not exit the containing scope. The next example is invalid because <code>adder</code> is a top-level definition (depending on compiler version, it could produce a correct result if compiled with no optimizing, i.e., at <code>-O0</code>): <syntaxhighlight lang="c"> #include <stdio.h> typedef int (*fn_int_to_int)(int); // type of function int->int fn_int_to_int adder(int number) { int add (int value) { return value + number; } return &add; // & operator is optional here because the name of a function in C is a pointer pointing on itself } int main(void) { fn_int_to_int add10 = adder(10); printf("%d\n", add10(1)); return 0; } </syntaxhighlight> But moving <code>adder</code> (and, optionally, the <code>typedef</code>) in <code>main</code> makes it valid: <syntaxhighlight lang="c"> #include <stdio.h> int main(void) { typedef int (*fn_int_to_int)(int); // type of function int->int fn_int_to_int adder(int number) { int add (int value) { return value + number; } return add; } fn_int_to_int add10 = adder(10); printf("%d\n", add10(1)); return 0; } </syntaxhighlight> If executed this now prints <code>11</code> as expected.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)