C++ function introduction
we know that functions play an important role in c program development. Dividing a program into modules or dividing a program into functions is one of the major principal of top down, structure programming. Another advantage of using functions is that it is possible to reduce the size of a program by calling functions and using them at different places in the program. recall that at different places in the program.
show();
main()
{
……
……
show();
……
……
}
void show()
{
……..
……..
……..
}
|
when the function is called , then control is transferred to the first statement with in the function body. Then other statements in the function body and then executed and control returns to the main function program when the closing brace is encountered.
C++ language is no exception. Functions continue to be the building blocks of C++ programs. In fact c++ has added many new features to functions to make them more reliable and also flexible. Like the c++ operators, a c++ function can be overloaded to make it perform different tasks depending on the arguments passed to it. most of these modifications are aimed at meeting the requirements of object oriented facilities
Main Function:
C language does’nt specify any return type for the main() function which is the starting point for the execution of a program. The definition of main() would look like this
this is perfectly valid because the main() in C language does’nt return any value In C++ language the main() returns a value of type int to the operating system. C++ language therefore explicitly defines main() as matching one of the following prototypes.
main();
main(int argc, char * argv[]);
|
the functions that have a return value should use the return statement for termination to the main() function in c++ language is, therefore, defined as follows:
since the return type of functions is int by default, the keyword int in the main() header is optional. Most C++ compilers will generate an error or warning if there is no return statement
turbo C++ issues the warning
Function should return a value in practical and then proceeds to compile the program. It is good programming practice to actually return a value from main()
Many operating system test the return value(called exit value) to determine if there is any problem. The normal convention is that an exit value of zero means the program run successfully, while a non zero(greater then 0) value means there was a problem. The explicitly use of a return(0) statement will indicate that the program was successfully executed