117

Can we have a nested function in C? What is the use of nested functions? If they exist in C does their implementation differ from compiler to compiler?

Sachin
  • 20,805
  • 32
  • 86
  • 99
  • 1
    Seems to be a duplicate of: http://stackoverflow.com/questions/1348095/why-are-nested-functions-not-supported-by-the-c-standard – zoli2k Apr 09 '10 at 14:21
  • 1
    also http://stackoverflow.com/questions/666586/are-nested-functions-part-of-c-standard and http://stackoverflow.com/questions/2256647/is-it-possible-in-c-or-c-to-create-a-function-inside-another and http://stackoverflow.com/questions/957592/functions-inside-functions-in-c and others taken from http://stackoverflow.com/search?q=nested+functions+[c] – dmckee --- ex-moderator kitten Apr 09 '10 at 14:56

9 Answers9

142

You cannot define a function within another function in standard C.

You can declare a function inside of a function, but it's not a nested function.

gcc has a language extension that allows nested functions. They are nonstandard, and as such are entirely compiler-dependent.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
43

No, they don't exist in C.

They are used in languages like Pascal for (at least) two reasons:

  1. They allow functional decomposition without polluting namespaces. You can define a single publicly visible function that implements some complex logic by relying one or more nested functions to break the problem into smaller, logical pieces.
  2. They simplify parameter passing in some cases. A nested function has access to all the parameters and some or all of the variables in the scope of the outer function, so the outer function doesn't have to explicitly pass a pile of local state into the nested function.
JimLohse
  • 1,209
  • 4
  • 19
  • 44
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
28

Nested functions are not a part of ANSI C, however, they are part of Gnu C.

zoli2k
  • 3,388
  • 4
  • 26
  • 36
  • What is there significance if they are part of Gnu C – Sachin Apr 09 '10 at 14:21
  • 5
    @Sachin Helps to realize why the C code with nested functions can be compiled with gcc. The information has educational value. Moreover, the question doesn't specified if it is limited only to C89, C99 or GNU C – zoli2k Apr 09 '10 at 14:35
  • 5
    Other languages supported by GCC do have them (ADA and Pascal that I know of), so it is likely that either it was easy to add to the C implementation or that it was added to C in order to make in preparation for supporting languages which require them. – nategoose Apr 09 '10 at 14:41
  • MATLAB also has nested functions. – mikeTronix Dec 20 '16 at 14:54
22

No you can't have a nested function in C. The closest you can come is to declare a function inside the definition of another function. The definition of that function has to appear outside of any other function body, though.

E.g.

void f(void)
{
    // Declare a function called g
    void g(void);

    // Call g
    g();
}

// Definition of g
void g(void)
{
}
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • 9
    If the function g is declared in this way, then what will be its scope? – Sachin Apr 09 '10 at 14:17
  • 6
    The declaration is scoped like any other declaration, so in this case until of the end of the function. Of course once the definition of `g` is visible later in the file that declaration is in scope for the rest of the translation unit. In addition you _can_ call functions in C without a visible declaration in scope even if it isn't advisable. – CB Bailey Apr 09 '10 at 14:27
8

I mention this as many people coding in C are now using C++ compilers (such as Visual C++ and Keil uVision) to do it, so you may be able to make use of this...

Although not yet permitted in C, if you're using C++, you can achieve the same effect with the lambda functions introduced in C++11:

void f()
{
    auto g = [] () { /* Some functionality */ }

    g();
}
Jon Green
  • 345
  • 2
  • 5
4

As others have answered, standard C does not support nested functions.

Nested functions are used in some languages to enclose multiple functions and variables into a container (the outer function) so that the individual functions (excluding the outer function) and variables are not seen from outside.

In C, this can be done by putting such functions in a separate source file. Define the main function as global and all the other functions and variables as static. Now only the main function is visible outside this module.

PauliL
  • 1,259
  • 9
  • 7
  • If there is recursion `outer`->`nested`->`outer`->`nested`, then there would be two different frames holding `int declared_in_outer`, so you can't just put `declared_in_outer` as a static global. – Adrian Panasiuk Nov 04 '13 at 18:31
3

To answer your second question, there are languages that allow defining nested functions (a list can be found here: nested-functions-language-list-wikipedia).

In JavaScript, which is one of the most famous of those languages, one may of nested functions (which are called closures) are:

  • To create class methods in constructors of objects.
  • To achieve the functionality of private class members along with setters and getters.
  • Not to pollute the global namespace (that goes for every language, of course).

to name a few...

kyriakosSt
  • 1,754
  • 2
  • 15
  • 33
-1

is this not a nested function in C? ( the function displayAccounts() )

I know I could have defined the function differently and passed variables and what not but anyhow works nicely as I needed to print the accounts multiple times.

(snipet taken from a school assignment)...

//function 'main' that executes the program.
int main(void)
{
    int customerArray[3][3] = {{1, 1000, 600}, {2, 5000, 2500}, {3, 10000, 2000}};  //multidimensional customer data array.
    int x, y;      //counters for the multidimensional customer array.
    char inquiry;  //variable used to store input from user ('y' or 'n' response on whether or not a recession is present).

    //function 'displayAccounts' displays the current status of accounts when called.
    void displayAccounts(void)
    {
        puts("\t\tBank Of Despair\n\nCustomer List:\n--------------");
        puts("Account #    Credit Limit\t  Balance\n---------    ------------\t  -------");
        for(x = 0; x <= 2; x++)
        {
            for(y = 0; y <= 2; y++)
                printf("%9d\t", customerArray[x][y]);
            puts("\n");
        }
    }

    displayAccounts();  //prints accounts to console.
    printf("Is there currently a recession (y or n)? ");


//...

    return 0;
}
  • 4
    It's not legal standard C. If it works with your compiler, it's because your compiler has provided an extension to the standard C language; in some sense your compiler is compiling a different language, which is, strictly speaking, not C. – Nate Eldredge Apr 13 '15 at 04:25
  • 1
    thank you for your input. I have since learned the proper way to declare, define and use functions. this is a bit embarrassing to look back on >. – midnightCoder Nov 16 '16 at 08:54
  • 2
    @midnightCoder: You can always delete your answer :) – chqrlie Jun 05 '19 at 06:01
  • There's plenty of older source-code that use it, like for example this link. Was it perhaps part of K&R C or just more common to see compiler support back then? https://history.dcs.ed.ac.uk/archive/languages/imp-pdp15/hdcomp.c.html – Christoffer Bubach May 14 '21 at 00:08
-2

Or you can be smart about it and use the preprocessor in your advantage (source.c):

#ifndef FIRSTPASS
#include <stdio.h>

//here comes your "nested" definitions
#define FIRSTPASS
#include "source.c"
#undef FIRSTPASS

main(){
#else
    int global = 2;
    int func() {printf("%d\n", global);}
#endif
#ifndef FIRSTPASS
    func();}
#endif
AnArrayOfFunctions
  • 3,452
  • 2
  • 29
  • 66
  • 1
    the fact you think it's "smart" to use the already-godawful preprocess language to hack around the godawful C language reflects poorly on your judgement – iono Jul 13 '22 at 05:30
  • @iono the fact that you comment on a 3 year old post just to criticise a working solution reflects poorly on your judgement. And btw I don't think it's your decision to make if the C language is "godawful" or not - it's still widely used. – AnArrayOfFunctions Jul 13 '22 at 09:48