Reputation: 1531
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 ?
Upvotes: 3
Views: 826
Reputation: 49108
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.
Upvotes: -1
Reputation:
Well known languages supporting lexically nested functions include:
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)"
Upvotes: 6
Reputation: 182664
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.
Upvotes: 2