質問

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.

役に立ちましたか?

解決

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

}

他のヒント

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

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top