Declaring a function?

2019-09-08 14:37发布

in C I am writing some of my very first exercises. Earlier on, I tried to declare a simple function inside of main and it comes with an error: "function definition is not allowed here". But I thought a function could be declared inside of main or outside, the only difference being the scope?? I have also read, in here, of other people writing functions inside of main, so why won't it let me do it? thanks

1条回答
Summer. ? 凉城
2楼-- · 2019-09-08 15:40

You can declare a function inside another function:

int main(void) {
    int foo(int); // declaration
    ...
}

But you can't define a function inside another function:

int main(void) {
    // Doesn't work.
    int foo(int x) {
        return x * 2;
    }
    ...
}

Also, declaring functions inside other functions is a really unusual thing to do, and essentially never necessary.

查看更多
登录 后发表回答