Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a function go after Main

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

like image 856
GPPK Avatar asked Jul 16 '13 11:07

GPPK


People also ask

Can a function be defined after Main?

If you define function after main() then you must provides it's prototype before main() first, ( so then after main , you can provide defination ).

Should functions go before or after main?

For a function defined in the same file where main is defined: If you define it before main , you only have to define it; you don't have to declare it and separately define it. If you define it after main , you have to put a matching prototype declaration before main .

Can we declare function after main in C?

In C you usually define function prototypes in header files, then include the header files, so functions can safely be defined after they are called.

Can we define function after main in Java?

No. One cannot directly define method in methods in java.


2 Answers

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 
.......;
}
like image 127
V. K. Jayendra Varma Avatar answered Sep 22 '22 12:09

V. K. Jayendra Varma


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.

like image 22
juanchopanza Avatar answered Sep 24 '22 12:09

juanchopanza