next up previous contents
Next: What does a pointer Up: Software Development and Coding Previous: getState(), setState(), and isProperty()   Contents

Parameter Passing

The appropriate use of pointers and references can simplify code, enhance readability, and greatly improve performance.



Parameter passing guidelines:

  1. If the data being passed is a primitive type and/or its size in bytes is small (less than the size of a pointer to that type), then it is acceptable to pass the parameter by value.
  2. Pass the parameter as a const reference if the data will not be changed within the function.
  3. Pass the parameter as a non-const pointer if the data will be changed inside the function.

Exceptions:

  1. If the name of the function implies a change to the passed object, it is acceptable to pass the parameter as a non-const reference, i.e. getNext(...), getText(...)
  2. If the parameters of the function where the function is frequently called are primarily pointers, then it is acceptable to pass parameters as non-const or const pointers.

The following is a demonstration of various parameter passing methods:


7#7

PrintMyStructOne(), the naive implementation, copies the CMyStruct data into its parameter ms, thus it copies 15,000 bytes of data. It is not desirable to copy this much data when it is not necessary.

PrintMyStructTwo() does not copy data, but when used, as in main() above, you must pass it a pointer. Passing a pointer implies that the data object could very well be modified within the function that is being called. Even though the parameter is a const in the function declaration, it is not clear from the perspective of main() that the function being called does not modify the object. The body of PrintMyStructTwo() is also slightly more complicated. Now you must deal with pointers and de-referencing within your function.

PrintMyStructThree() does not copy data, and because you do not pass it a pointer to the object, it does not imply that the function will be changing the passed object. Note that the body of PrintMyStructThree() and the naive method PrintMyStructOne() are the same. Also Note that the call in main() to PrintMyStructThree() looks exactly the same as the call to the naive method PrintMyStructOne(). It is just as simple to use as the naive method and looks cleaner than the pointer approach in PrintMyStructTwo().



Subsections
next up previous contents
Next: What does a pointer Up: Software Development and Coding Previous: getState(), setState(), and isProperty()   Contents
Falko Kuester 2001-08-24