Search code examples
c++function-prototypes

Why prototype is required even without any class declaration?


If I just do it: Ex1:

#include <iostream>

int main()
{
    //try to call doSomething function
    doSomething();
}

void doSomething()
{
    std::cout << "Call me now!" << std::endl;
}

I get compilation error! Because the compile doesn´t know what is "doSomething".

But if I change the position of doSomething to come in first place, the program compiles successfully. Ex2:

#include <iostream>

void doSomething()
{
    std::cout << "Call me now!" << std::endl;
}

int main()
{
    //try to call doSomething function
    doSomething();
}

I can declare prototype to be like this: Ex3:

#include <iostream>

void doSomething(void);

int main()
{
    //try to call doSomething function
    doSomething();
}

void doSomething()
{
    std::cout << "Call me now!" << std::endl;
}

But why the first example does not work? Why I even have to declare a prototype or call functions first and main function at last?

Thanks!


Solution

  • You can't call a function without the compiler having seen either the definition or a declaration, first -- simple as that. A prototype or the actual definition must appear before a call.