Search code examples
cconventionsnested-function

Defining a Function inside of main()


Out of curiosity, is it considered poor practice to define a function inside of main() in C?

My problem with the current program I am writing is that I have 20 some pointers to structs that are defined inside of main() (the pointers, not the structs themselves, those are in other files), and I have a block of code that needs to be called several times with different parameters, and it must have the ability to modify any of the pointers. The only solution I found (I am a novice in C) was to define a function inside of main() that has the correct scope to modify any of the pointers.


Solution

  • Nested functions (functions within functions) is a GNU only extension and not part of any regular C standard. Any other compiler will fail to compile this. Due to this I would highly discourage the use of nested functions.

    Declare your structs and functions outside. You can then always pass a pointer to your data structures to your function.

    struct s {...};
    
    void foo(struct s *, ...);
    
    int main() {
    
      struct s mystruct;
      foo(&mystruct, ...);
    
    }