[英]Why can't a function go after Main
Why can't I put a function after main, visual studio cannot build the program.为什么我不能在main之后放一个函数,visual studio无法构建程序。 Is this a C++ quirk or a Visual Studio quirk?
这是 C++ 的怪癖还是 Visual Studio 的怪癖?
eg.例如。
int main()
{
myFunction()
}
myFunction(){}
will produce an error that main cannot use myFunction会产生 main 不能使用 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
.如果函数不返回任何内容,则该类型必须为
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.编译器不知道
i
是什么——它并不真正关心它会是什么。
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.
当我们在 main 函数之后定义一个函数并在 main [myFunction () ] 中使用它时,编译器会认为“这是什么。我以前从未见过这个”并产生一个错误,说 myFunction 未声明。 If you want to use in this way you should give a prototype for that function before you define main function.
如果你想以这种方式使用,你应该在定义 main 函数之前给出该函数的原型。 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.
这通常是 C++ 行为。
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.你必须向前声明一个函数,这样 main 才能知道有一些。
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(){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.