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()
{
myFunction()
}
myFunction(){}
will produce an error that main cannot use myFunction
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
.
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
.......;
}
Because
myFunction()
has to be declared before using it. This is c++ behaviour in general.
Functions need to be declared before they can be used:
void myFunction();
int main() {
myFunction();
}
void myFunction() {
...
}
you have to forward declare a function so main can know that there is some.
void myFunction();
int main()
{
myFunction();
}
void myFunction(){}
Don't forget about putting ;
after each command.
在调用函数之前指定函数声明。这样编译器就会知道返回类型和签名
Declare then define.
void func();
int main()
{
func();
}
void func()
{
}
You have to declare the function before.
void myFunction();
int main()
{
myFunction()
}
myFunction(){}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.