What will happen when a function defined within another function? What is the difference between code 1 and code 2?
CODE 1:
#include<stdio.h>
void m();
void main()
{
m();
void m()
{
printf("hi");
}
}
CODE 2:
#include <stdio.h>
void m();
void main()
{
void m()
{
printf("hi");
}
m();
}
When I compiled code 1 in gcc compiler, I got linkage error. But when I compiled code 2, I didn't get any error. I got output "hi". I want to know how compilation is done, when we write function definition within another function. I know that when we write function definitions not within another function, wherever be the function definition, we will not get any error when we call that function. for example see the below code:
CODE 3:
#include <stdio.h>
void m();
void main()
{
m();
}
void m()
{
printf("hi");
}
In code 3,even though I called the function before definition, it didn't show any error and I got output. Why it is not happening with code 1.
Neither C nor C++ allows to define a function within another function. So it seems you are using a special language extension of compiler GCC that allows to define local functions inside another functions.
In the first program function m is declared in file scope. So its definition will be searched by the compiler in the file scope. When the function is called inside main only this file scope declaration is visible. However the compiler did not find its file scope definition so it issued an error.
In the second program there is also a declaration of function m in the file scope. However inside function main there is another declaration of function m that has block scope and hides the declaration with the file scope. Take into account that a definition also is a declaration. So the call of m refers to the function m that is declared inside main and has block scope. The compiler has the function definition and can call it.
in the third program that satisfies the C Standard inside main the call of m refers to the function m declared in the file scope and there is a definition of this function in the file scope. So there is no any problem.
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