简体   繁体   中英

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

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");
    }
}

You can not implement a function within the scope of another function in standard C. Move the implementation of m() out of your main.

The code you posted should not compile at all; though, the error you get is because the linker ld can not find the implementation of m . The function can be used because you declared it, but the implementation is missing and thus can not be linked.

Also note that your main function shall return a value of type int . Using void will make your program return an arbitrary value from which the operating system/shell can't conclude whether execution was successful.

#include <stdio.h>

void m();

void n() {
    m();
}

int main() {
    n();
    return 0;
}

void m() {
    printf("hi");
}

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

Some compilers (eg gcc) allow it as an extension. But then the function is local , ie 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.

m()的函数声明移到main()方法之外。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM