2

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.

fr00ty_l00ps
  • 722
  • 3
  • 8
  • 22
  • It's not a poor practice, you simply can't. – Maroun Apr 08 '14 at 13:17
  • GCC didn't have a hissy fit, and it ran as planned... As my luck would have it, I am on a different computer than I wrote the code on, and cannot share what I have... – fr00ty_l00ps Apr 08 '14 at 13:18
  • Use `-pedantic` and it will complain: `warning: ISO C forbids nested functions ` – Shafik Yaghmour Apr 08 '14 at 13:19
  • 1
    @MBlanc Agreed. I have flagged it as a duplicate. My apologies. – fr00ty_l00ps Apr 08 '14 at 13:21
  • 1
    `"I have 20 some structs that are defined inside of main()"`. That's your core problem, you have no program design. The solution to your problem isn't to obfuscate your program even more, but to divide your program into independent modules, using an object-oriented approach, where every module only knows about its own task only. – Lundin Apr 08 '14 at 13:29
  • @Lundin I was not clear. I have the struct definitions themselves in a different file, but the physical variables (I would have said objects) are defined in `main()`. See the Q now, as I have fixed it – fr00ty_l00ps Apr 08 '14 at 13:30
  • Still, the need to create strange things like these almost certainly originates from muddy program design. – Lundin Apr 08 '14 at 13:34

3 Answers3

5

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, ...);

}
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
5

GCC allows it, but it is a non-standard extension specific to that compiler - so your code won't compile on any other compiler

Anonymouse
  • 935
  • 9
  • 20
0

Gcc compiler allows you to define methods inside other methods (this is a Gnu extension, actually). But, usually, it is a bad practice.

In your case this is the only way for your method to know about this specific types. But I would recommend you to make your types external and declare methods that use this types in normal way (outside of any other method).

mesmerizingr
  • 1,417
  • 1
  • 18
  • 25