0

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

Rob
  • 26,989
  • 16
  • 82
  • 98
Dave
  • 81
  • 7

1 Answers1

3

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505