Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does nested function mean in C?

Tags:

c

syntax

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 ?

like image 449
R__ Avatar asked Jun 22 '26 20:06

R__


2 Answers

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.

like image 29
cnicutar Avatar answered Jun 24 '26 09:06

cnicutar