4.3 Pass-by-reference, C

C has no pass-by-reference mechanism. When a subroutine needs to modify an object or variable that does not belong to it, it needs to resort to pointers. In our example, this is how a C subroutine looks like:

void inc(int *pInt)
{
  *pInt = *pInt + 1;
}

pInt is a pointer to an integer. The value of pInt is not an integer, but the address of the storage of an integer. In the statement in the subroutine, *pInt refers to ``whatever integer pInt points to.'' On the left hand side of the assignment, *pInt specifies where to store the result of the right hand side.

Although this can accomplish the same as the C++ code in section 4.2, it is also more dangerous. Let us consider the following incorrect code:

void inc(int *pInt)
{
  pInt = pInt + 1;
}

This code compiles just fine, it may generate a warning message. However, it does not do what the earlier code does. pInt refers to the parameter itself. The assignment statement increments the pointer itself, but it does not do anything to what the pointer points to. There is no dereference operator!

This is why C++ includes a true pass-by-reference mechanism.

Copyright © 2006-08-28 by Tak Auyeung