tags:

views:

211

answers:

4

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?

+1  A: 

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

banister
+14  A: 

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.

Mark Rushakoff
Note also that even gcc supports it for C only, not C++.
Pavel Minaev
A: 

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.

jmbr
A: 

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.

joe
By "visibility" do you mean access? In that case, that would be quite specific and unlike other semantics.
Potatoswatter
Yes, the embedded functions have, as far as I can tell, the same scoping as any other block inside a function. From that GCC link in a previous comment, "The nested function can access all the variables of the containing function that are visible at the point of its definition. This is called lexical scoping. For example, here we show a nested function which uses an inherited variable..."
joe