Justin Ethier
Justin Ethier

Reputation: 134207

Nested Functions in C - Best Practices

I just realized a function may be defined inside another function in C:

void main(){
  int foo(){ return 2; };
  printf("%d\n", foo());
}

Besides being a neat trick, the useful thing about this is that the inner function is private to the outer function. But... is that a good enough reason to do this in a "real-world" application? What are the best practices for using this syntax?

Upvotes: 3

Views: 901

Answers (4)

joe
joe

Reputation: 31

If I remember correctly, embedded functions have visibility to their parent functions' symbols. In some circumstances, maybe this could be useful to avoid global variables (help with thread safety?) As this feature is GCC specific, I would seek to avoid it unless I really needed it.

Upvotes: 1

jmbr
jmbr

Reputation: 3348

If you are writing a compiler that translates Pascal (which allows nested procedures) into C and relies on GCC to turn the result into a binary, then this functionality is certainly useful.

Upvotes: 1

Mark Rushakoff
Mark Rushakoff

Reputation: 258348

Nested functions are a non-standard extension, implemented by GCC (and maybe others that I don't know about). Seeing as it does not follow a standard, best practices probably include not using it in code you intend to be portable.

If your ultimate goal is to have "private" functions in C, then you are better off using separate files and making the "private" functions static so that they won't be linked to other object files.

Upvotes: 15

horseyguy
horseyguy

Reputation: 29915

I think this is a compiler extension rather than part of the C spec itself

see: http://discuss.joelonsoftware.com/default.asp?interview.11.431470.11

Upvotes: 1

Related Questions