Why the function does not work after Main

Why can't I add a function after main, visual studio cannot create a program. Is this a C ++ quirk or a Visual Studio quirk?

eg.

int main() { myFunction() } myFunction(){} 

will result in an error that main cannot use myFunction

+4
source share
9 answers

You can, but you must declare this in advance:

 void myFunction(); // declaration int main() { myFunction(); } void myFunction(){} // definition 

Please note that functions require a return type. If the function returns nothing, this type must be void .

+19
source

You cannot use a name / character that has not yet been declared. That is the whole reason.

This is true:

 i = 10; //i not yet declared int i; 

This is not true , for exactly the same reason. The compiler does not know that i is - it does not matter to him what it will be.

Just like you write this (which also makes sense for both you and the compiler):

 int i; //declaration (and definition too!) i = 10; //use 

you should write this:

 void myFunction(); //declaration! int main() { myFunction() //use } void myFunction(){} //definition 

Hope this helps.

+8
source

Because the

 myFunction() 

must be declared before using it. This is generally C ++ behavior.

+1
source

Functions must be declared before using them:

 void myFunction(); int main() { myFunction(); } void myFunction() { ... } 
0
source

you need to forward the function declaration, so the main one may know that there are some.

 void myFunction(); int main() { myFunction(); } void myFunction(){} 

Do not forget about the placement ; after each team.

0
source

Of course you can, declare it first. Or better, put the declaration in the header and #include in the source file.

 void myFunction(); int main() { myFunction(); } void myFunction(){} 
0
source

specify the function declaration before calling the function. So this compiler will know about the return type and signature

0
source

You must declare a function before.

 void myFunction(); int main() { myFunction() } myFunction(){} 
0
source

most programming languages ​​have a top-down approach, which means the code is compiled from above. When we define a function after the main function and use it in main [myFunction ()], the compiler thinks "what it is. I have never seen this before," and it generates an error by declaring that myFunction has not been declared. If you want to use this way, you must specify a prototype of this function before defining the main function. But some compilers accept without a prototype.

 #include<stdio.h> void myFunction(); //prototype int main() { myFunction(); //use } myFunction(){ //definition .......; } 
0
source

Source: https://habr.com/ru/post/1491642/


All Articles