The main() Function

 < Day Day Up > 



Every C++ program contains a main() function. You may write library routines that do not contain a main function but the program that ultimately uses them will have a main() function. This section will briefly discuss the purpose of the main() function and the two forms it can take.

The Purpose of the main() Function

The main() function marks the start of program execution. A program may be small and contain only a main() function that itself only contains a few simple statements, or it may be huge and be comprised of many different objects and stand-alone functions that are defined across thousands of files and millions of lines of source code. What ever form it takes, it all starts with main().

Two Forms of main()

The main() function can be written two ways. You have seen the first, and most simple, form of writing main() in this chapter already:

int main(){    // some statements here    return 0; }

The second way to write main() looks like this:

int main(int argc, char* argv[]){    //process command line input    //along with other statements here    return 0; }

This form of main() is used to write programs that process command line arguments. If you have used DOS or UNIX you have probably used utility commands that required command line arguments to run properly.

Exiting main()

There are several ways to exit the main() function. You seen one way used throughout this chapter and that is by using the keyword return followed by a 0. This is actually the lazy way of doing things, mainly because having the value 0 in a statement gives no clue to what 0 means.

It just so happens that the value 0, when returned from main(), means the program executed successfully. In fact there is a constant already declared for your use called EXIT_SUCCESS. You will find it and some other cool stuff in the cstdlib header file. (stdlib.h on older C or C++ environments) Here is an example of using EXIT_SUCCESS:

int main() { // amazingly clever code goes here... return EXIT_SUCCESS; }

Instead of using the return keyword you can use the function exit(int status):

int main(){ //code gone bad exit(EXIT_FAILURE); }

In chapter 7 you will see other ways to use the exit() function and what effects it has on objects in your program.

Calling Functions Upon Exiting main()

Use the atexit(void (*func)(void)) to register a function you want called when the exit() function is called. Example 5-8 gives the code:

Example 5.8: Registering Functions with atexit()

start example

click to expand

end example



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net