next up previous contents index
Next: Mathematical Functions Up: More About C++ Previous: Names and Types   Contents   Index

Functions

In a programming language, the term ``function'' refers to a block of code that is executable by name. A C++ function takes a list of ``arguments'', and has a ``return value''. This information, together with the function's name, must be provided when a function is defined. A function may not be defined inside another function. However, a function may call other functions (including itself) as part of its execution:

  int factorial(unsigned int n)
  {
    if (n == 0) return 1;
    else return n*factorial(n-1);
  }

The special type void represents a ``null type''. A function that performs an action but does not return a value has return type void. A function that takes no arguments may be viewed as taking a single void argument.

Every C++ program has a special function main(), which is called by the operating system when the program is run. The arguments of main() are command-line arguments, and the return type is an integer that signals success or failure. User-specified functions must be defined before the call to main() or in a separately-compiled file.

Functions in C++ may be as simple as an algebraic formula or as complex as an arbitrary algorithm. Greatest common divisors, finite sums, numerical derivatives and integrals, solutions of differential equations, recursively generated fractal curves, and curves of best fit are a few applications in ePiX. Several sample files contain user-level algorithms, which do not require knowledge of ePiX's internal data structures. The source file functions.cc contains simple functions defined by algorithms, and functions.h illustrates the use of C++ templates. Other source files, such as plots.cc, may be consulted for Simpson's rule, Euler's method, and the like.

An error, such as division by zero or an attempt to intersect parallel lines, may occur when a function is executed. In this situation, a C++ function can ``throw an exception'', or return an error type that the caller ``catches'' and handles. If an uncaught exception is thrown, the program terminates. ePiX's intersection operators throw exceptions when certain conditions are not met.


next up previous contents index
Next: Mathematical Functions Up: More About C++ Previous: Names and Types   Contents   Index
Andrew D. Hwang 2004-09-04