next up previous contents
Next: 8.6 Command Line Options Up: 8. A More Modular Previous: 8.4 Include Statements, Function

8.5 The Function main()



\begin{Code}[nbody\_sh1.C: main]
\small\verbatiminput{chap8/nbody_sh1.C.3_main} \end{Code}

The first six variables declared at the top of main() receive their values from the function read_options() which reads the Unix style command line arguments. Note that each variable has a default value, which is retained unless it is changed explicitly by the corresponding command. We discuss the usage of command line options in the next section.

If the function read_options() detects a request for help, or the invocation of a non-existent option, it will return the Boolean value false. In that case the statement !read_options() is true, and program execution is halted. In C++, returning the value 0 indicates normal successful completion of the main() program, while any other value indicates a failure of some kind or other. For simplicity we return here the value 1.

Once the options are interpreted, we are ready to read the $N$-body snapshot from the standard input (which typically is redirected to read either the contents of a file, as in nbody_sh1 < data.in or to receive data from another program through a pipe, as in generate_data | nbody_sh1). Once the number of particles n has been read in, we can allocate storage space to contain the masses and dynamical information for all n particles, as we have seen in the previous chapter. The actual initialization of the arrays is carried out by the function get_snapshot().

The real work is then delegated to the function evolve(), which oversees the evolution in time of the $N$-body system. When the call to evolve() returns, there is nothing left to be done. For good form we then deallocate the memory that we had dynamically allocated with the new operator. Note the square brackets in delete, which tell the compiler to delete the full memory assigned to the arrays. If we left this out, for example in a statement delete[] mass, we would only free the memory for mass[0]. This would constitute a memory leak, since the rest of the array will still be allocated, but it will be no longer usable in our program. In our particular case, this is no problem since we are about to terminate the program anyway, but in more complex cases, such as we will encounter in the function evolve(), it will be important to not create memory leaks.


next up previous contents
Next: 8.6 Command Line Options Up: 8. A More Modular Previous: 8.4 Include Statements, Function
The Art of Computational Science
2004/01/25