Thursday, July 30, 2009

In C++ how do you get a function to display something without int main()?

for example


#include %26lt;iostream%26gt;





using namespace std;





int Sum_twonumbers(int sum)


{


sum = 10;


cout %26lt;%26lt; "this is the value of the sum function:" %26lt;%26lt; endl;


cout %26lt;%26lt; sum %26lt;%26lt; endl;


return sum;


}





It compiles In Visual C++ 2008 edition but gets build errors. I'm still learning functions and I wanted to see if this was possible without including variables in int main (). Is this possible or do you have to call the fuction from int main() in order to work?

In C++ how do you get a function to display something without int main()?
in every c/c++ program, a main() function is always required, as many and my mentor have said, it is the entry point from where your program should start.


you can use instead a void function inside the main function.





int main()


{


sum_twonumbers();


}


int Sum_twonumbers(int sum)


{


sum = 10;


cout %26lt;%26lt; "this is the value of the sum function:" %26lt;%26lt; endl;


cout %26lt;%26lt; sum %26lt;%26lt; endl;


return sum;


}


something like this. hope this helps


cheers.
Reply:The function main() is must for a complete program to work... thats where the execution of program starts...





In VC++ it might have compiled because , here you can put functions in different files and compile them separately ... But when you you try to build the complete program LINKER will flag an error as it see no main() in the program...





Remember main() is the function where the execution starts in any C/C++ program.
Reply:In every c++ program, the only part that is ACTUALLY executed is the main() function. The other functions are not recognized as executable parts.


So you can compile a program without main(), but you can't run it!


No comments:

Post a Comment