Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 340
Ito Avatar asked Jan 19 '23 06:01

Ito


2 Answers

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.

like image 120
Ernest Friedman-Hill Avatar answered Jan 30 '23 16:01

Ernest Friedman-Hill


Because the compiler hasn't seen doSomething before it's used.

Either you must prototype it, or define it first, so that the compiler knows how to analyze the usage of it.

like image 38
Mordachai Avatar answered Jan 30 '23 16:01

Mordachai