Why does this compile?
int main() {
void f();
}
What is f
? Is it a function or a variable and how can I use it?
Nested function is not supported by C because we cannot define a function within another function in C.
A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation .
Variable Declaration in C You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.
The declaration of a user-defined function inside the main() function and outside main() is similar to the declaration of local and global variables, i.e. When we declare a function inside the main, it is in local scope to main() and that function can be used in main() and any function outside main() can't access the ...
You have a function declaration. It's OK to declare functions inside a block scope. It's just not possible to define a function in a block. Declaring a function only locally is perfectly fine, e.g. when you want to refer to some other, existing function:
int main()
{
int foo();
return foo();
}
You just have to link this with some translation unit that defines int foo();
.
(It's probably just not very good practice to do this, since it hides the dependency of your code on the other function in a way that's almost impossible to see without careful reading of the code.)
Note that the local declaration hides other overloads of the function, so argument lookup may be different from if you had declared the function at the global scope. See @David Rodríguez's vastly more detailed answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With