UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

5.7.  Indirection use

The use of pointers in C is only justified if they offer a clear advantage compared to manipulating the data directly. It follows the description of two scenarios in which the use of pointers translates into more efficient code, that is, a program that executes faster, or a program that occupies less space in memory.

5.7.1.  Parameters passed by reference

Sometimes, we are interested on creating functions in which the value of the parameters sent in the function have to be modified inside the function and maintained outside the function environment. In this case, we say that we are passing the parameters by reference. When passing the parameters by reference, the compiler does not copy the value of the argument (as we have already seen in the previous section about function), but sends to the function a reference indicating the position of the variable in the memory. That is to say, when passing the memory address, if we change the value of the variable, we are changing the variable itself and not its copy. An example of these types of functions is the function "swap". The function "swap" receives two parameters and swap their values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 #include <stdio.h>
     
      /* Defining the function "swap". Notice that the parameters are received as pointers.*/
     void sswap ( int *x, int *y )
      {
          /*Delcaring the temporal variable*/
          int tmp;
          tmp = *x;
          *x = *y;
          *y = tmp;
      }
      
      int main() 
      {
            int a, b;
            a = 1;
            b = 2;

            /*Calling the function "swap" passing a and b by reference.*/
            swap( &a, &b );
            /*This prints the values of a and b swapped*/
            printf(" a = %d b = %d\n", a, b );

      }
     

Copy this code and execute it. You will see how the values of a and b are swapped. This is because the function receives the parameters by reference or, what is the same, the function receives the memory address of the parameters. When, inside the function, the values of a and b change, it is the content of the memory address sent what is changed. For this reason, outside the function environment, a and b maintain the changes suffered inside the function.

Suggestion

Modify the previous program without passing the parameters by reference. You will see that, outside the function, the values of a and b have the values assigned in their declaration.