Can you nest functions in C?
By Flavio Copes
Can you nest functions in C? No, you can't define a function inside another like in JavaScript or Python, so split helpers into a separate file instead.
No, you can’t.
We can’t define functions inside other functions in C.
With languages like JavaScript, Swift or Python it is pretty common to use nested functions.
C and C++ do not provide this option.
What happens if you try
Say you try to define a helper inside main():
#include <stdio.h>
int main(void) {
int double_it(int n) {
return n * 2;
}
printf("%d\n", double_it(21));
return 0;
}
Compiling this with clang stops right away:
nested.c:4:24: error: function definition is not allowed here
In C, every function definition lives at the top level of a file. The language has no closures, so a nested function would have no standard way to capture the variables of the enclosing function anyway.
One caveat: GCC accepts nested functions as a GNU extension. It’s non-standard, clang rejects it, and other compilers do too, so I’d stay away from it. Code that only compiles on one compiler is a problem waiting to happen.
What to do instead
If the goal is just organizing code, define the helper next to the function that uses it:
#include <stdio.h>
int double_it(int n) {
return n * 2;
}
int main(void) {
printf("%d\n", double_it(21)); /* 42 */
return 0;
}
Often the reason we want nested functions is hiding: the helper is an implementation detail, and we don’t want the rest of the program calling it.
C has a tool for that: the static keyword. A static function is only visible inside the file where it’s defined:
static int double_it(int n) {
return n * 2;
}
Other files can’t call it, and it won’t clash with a function that has the same name somewhere else in the program.
For bigger programs, your next best option is to put the functions you need to perform something in a separate file, and only expose the primary function a client program needs to use, so you can “hide” all the things that does not need to be public.
Declare the public function in a header file, mark everything else static in the .c file, and you get the same encapsulation nested functions would give you, in idiomatic C.
Want me to talk about your product? You can sponsor this site.