5.13.4. Passing Structures as Parameters

If you pass a structure using call-by-value, the function has a local variable that is initialized to a copy of the structure, just as would happen if you passed an integer by value. For example, if print is defined by

  void print(Cell c)
  {
    ...
  }
then when print(e) is called, the contents of structure e is copied into a local variable, c, of type Cell, in the frame for print. Any change that print makes to c will only affect that local copy.

Usually, you do not want to copy a structure. It takes time and memory to do that. Instead, you prefer to pass a structure using either call by reference or call by pointer. If you do not intend to change the structure, mark it as const. For example, a more typical definition of print would begin

  void print(const Cell& c)
  {
    ...
  }


Exercises

  1. Using type Complex from the preceding page, define function sum(a,b,c) that takes two complex numbers a and b (as in-parameters), and sets out-parameter c equal to the sum of a and b. The definition of the sum is that c.impart = a.impart + b.impart and c.repart = a.repart + b.repart. Answer

  2. A function is allowed to return a structure. Redo the preceding exercise, but this time make sum have only the two in-parameters, and make it return the answer. (Returning a structure requires copying the structure, so it is usually a fairly slow way to do things, but you can do it in places where efficiency is not a big deal.) Answer

  3. Write a function re(z) that returns the real part of Complex number z. Answer