Nested function in C

CFunctionNested

C Problem Overview


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?

C Solutions


Solution 1 - C

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.

Solution 2 - C

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.

Solution 3 - C

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

Solution 4 - C

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)
{
}

Solution 5 - C

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();
}

Solution 6 - C

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.

Solution 7 - C

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...

Solution 8 - C

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;
}


    

Solution 9 - C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSachin ChourasiyaView Question on Stackoverflow
Solution 1 - CJames McNellisView Answer on Stackoverflow
Solution 2 - CMarcelo CantosView Answer on Stackoverflow
Solution 3 - Czoli2kView Answer on Stackoverflow
Solution 4 - CCB BaileyView Answer on Stackoverflow
Solution 5 - CJon GreenView Answer on Stackoverflow
Solution 6 - CPauliLView Answer on Stackoverflow
Solution 7 - CkyriakosStView Answer on Stackoverflow
Solution 8 - CmidnightCoderView Answer on Stackoverflow
Solution 9 - CAnArrayOfFunctionsView Answer on Stackoverflow