next up previous contents
Next: 10 Performance Up: IMPL_repdoc Previous: 8 Function Pointers   Contents

9 Optional Arguements in C++

Code for the example is in opt_arg.C. This code demonstrates the ideas below with a different yet similar example.

Optional arguments in F90 are more flexible than their counterparts in C++. Whereas F90 allows the arguments to be specified in any order, C++ demands that the arguments be placed in the same order as the function prototype. However, there is a standard trick to get around this that has been around even prior to C++, and that has been used successfully in C in such libraries as the Xwindows system. For example,

/* Example of an Xwindows call to retrieve information about
   a window. */
XtVaGetValues(XtParent(w),
              XmNnumChildren, &numkids,
              XmNchildren, &kids,
              NULL);

The call above asks a window to get all of its sibling windows. Windows (as objects) have many attributes (foreground colors, background color, size, stacking behavior, etc...) and, obviously, if only some of these attributes are desired one does not want to have to ask for anything more than what is needed. Yet, at the same time, the programmer does not want to have to provide a different accessor function for every possible combination of attributes a user might want.

The trick is to use C stdargs and a list of name, attribute pairs. The prototype of the above call is,

extern void XtVaGetValues(
    Widget              /* widget */,
    ...
);

The dots above are the signal that an unknown number of arguments will follow. In the previous call, XmNnumChildren and XmNchildren are some type of either enumeration or pound defined constants. In the routine, code parses each argument, first getting the XmNnumChildren attribute. This tells the code what type of argument to expect next, and this argument can be pulled off the call stack with the va_arg call. See man stdarg for more details on the use of this library.

The arguments may be sent in any order, since the code parses each pair separately. Also, any number of arguments may be either included or excluded, as they are parsed dynamically. The very last argument in this type of call is typically a NULL, since the list needs to know when to quit processing.


next up previous contents
Next: 10 Performance Up: IMPL_repdoc Previous: 8 Function Pointers   Contents
esmf_support@list.woc.noaa.gov