Pwnna
Pwnna

Reputation: 9538

Why can I not define main() first, and then the functions which it calls?

If I put main on the top of the source file and invoke some custom functions, it will tell me that those functions are not found, but if I put main on the bottom of the source file, it will work.

Why? Is it because the compiler parses the program from top to bottom and breaks at the definition of main?

Upvotes: 3

Views: 3317

Answers (4)

EboMike
EboMike

Reputation: 77762

It has nothing to do with main. C++ compilers work top to bottom, period.

Anything that you reference needs to be declared previously. The same goes for variables. In your case, you could do

void foo();     // <-- Forward declaration, aka prototype

int main() {
   foo();
}

void foo() {
   // Here is your foo implementation.
}

Upvotes: 15

Eton B.
Eton B.

Reputation: 6291

If main is declared before your custom functions, by the time main gets parsed it hasn't 'seen' any definitions for them.

Upvotes: 0

anon
anon

Reputation:

Basically, yes. You have to define/declare a function before you can use it.

Upvotes: 4

Byron Whitlock
Byron Whitlock

Reputation: 53921

You should be putting your functions signature into header files that are included before main().

Upvotes: 0

Related Questions