Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we define function inside the main function?

Tags:

c

In the following program, I try to call the function n() and inside n(), try to call m() function which is defined in the main function, but when I compile, I get the error below:

In function `n':
(.text+0xa): undefined reference to `m'
error: ld returned 1 exit status

Why do I get an error? Please explain.

The code is here:

#include <stdio.h>
void m();
void n()
{
    m();
}

void main()
{
    n();
    void m()
    {
        printf("hi");
    }
}
like image 553
msc Avatar asked May 18 '26 03:05

msc


1 Answers

m is defined inside of main. In standard C, that's not allowed (you can't define a function within another function).

Some compilers (e.g. gcc) allow it as an extension. But then the function is local, i.e. m only exists within main and can't be seen from the outside. Similarly, variables defined within a function are local to that function and can't be seen from the outside.

Your void m(); declaration at the top claims that a (global) function called m exists, but it doesn't. That's why you get the linker error.

like image 160
melpomene Avatar answered May 20 '26 23:05

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!