Why can\'t I put a function after main, visual studio cannot build the program. Is this a C++ quirk or a Visual Studio quirk?
eg.
int main()
{
myF
You can, but you have to declare it beforehand:
void myFunction(); // declaration
int main()
{
myFunction();
}
void myFunction(){} // definition
Note that a function needs a return type. If the function does not return anything, that type must be void
.
Functions need to be declared before they can be used:
void myFunction();
int main() {
myFunction();
}
void myFunction() {
...
}
You cannot use a name/symbol which is not yet declared. That is the whole reason.
It is like this:
i = 10; //i not yet declared
int i;
That is wrong too, exactly for the same reason. The compiler doesn't know what i
is – it doesn't really care what it will be.
Just like you write this (which also makes sense to you as well as the compiler):
int i; //declaration (and definition too!)
i = 10; //use
you've to write this:
void myFunction(); //declaration!
int main()
{
myFunction() //use
}
void myFunction(){} //definition
Hope that helps.
most of the computer programming languages have top to down approach which means code is compiled from the top. When we define a function after main function and use it in the main [myFunction () ], compiler thinks " what is this. I never saw this before " and it generates an error saying myFunction not declared. If you want to use in this way you should give a prototype for that function before you define main function. But some compilers accept without a prototype.
#include<stdio.h>
void myFunction(); //prototype
int main()
{
myFunction(); //use
}
myFunction(){ //definition
.......;
}
specify the function declaration before calling function .So that compiler will know about return type and signature
Because
myFunction()
has to be declared before using it. This is c++ behaviour in general.