开发者

What does nested function mean in C?

void t(){
    printf("hello\n");
    void s(){
        printf("2\n");
    }   
}
int main(){
    t();
    return 0;                                                                                                                                 
}

After I call t(), s should be defined, but seems 开发者_开发知识库it's not the case.

Is it just ignored ?


Well known languages supporting lexically nested functions include:

  • ALGOL-based languages such as ALGOL 68, Simula, Pascal, Modula-2, Modula-3, Oberon and Ada.
  • Modern versions of Lisp (with lexical scope) such as Scheme, and Common Lisp.
  • ECMA Script (JavaScript, and ActionScript).
  • Full support in Scala
  • Various degrees of support in scripting languages such as Ruby, Python, and Perl (starting with version 6).
  • There is also a C-related language with nested functions, the D language.
  • GCC also supports nested functions in C, as a language extension.1
  • Fortran, starting with Fortran-90, supports one level of nested (CONTAINed) subroutines and functions.

In your case, function s will only be available within t.

A nested function is a function defined inside another function. (Nested functions are not supported for GNU C++.) The nested function's name is local to the block where it is defined. For example, here we define a nested function named square, and call it twice:

 foo (double a, double b)
 {
   double square (double z) { return z * z; }

   return square (a) + square (b);
 }

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 named offset:

 bar (int *array, int offset, int size)
 {
   int access (int *array, int index)
     { return array[index + offset]; }
   int i;
   /* ... */
   for (i = 0; i < size; i++)
     /* ... */ access (array, i) /* ... */
 }

Nested function definitions are permitted within functions in the places where variable definitions are allowed; that is, in any block, mixed with the other declarations and statements in the block.

See "Nested Functions - Using the GNU Compiler Collection (GCC)"


Actually s will only be available within t. Quoting the link posted by In silico:

The nested function's name is local to the block where it is defined.


In C, functions and their scope (where their name can be used) are defined and fixed at compile time. If you want to change what a function name does during runtime, you need to use function pointers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜