|
If you pass a structure using call-by-value, the function has a local variable that is initialized to a (shallow) copy of the structure that is passed, 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 (shallow) copy.
(Of course, the standards for this course require
you not to change a call-by-value parameter, so you
would not do that.)
Usually, you do not want to copy a structure. It takes time and memory to do that. Also, in practice, structures often contain pointers, and you must remember that the copy is shallow.
Most often, it is preferred 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)
{
...
}
Using type Complex from a prior exercise, 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
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
Redo the preceding exercise, but make your function return a pointer to a Complex structure. Answer
Write a function re(z) that returns the rePart of Complex number z. Answer
|