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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With