Page 85 - Programming Microcontrollers in C
P. 85

70     Chapter 2  Advanced C Topics

            Pointers and Function Arguments
                              Values passed to functions as arguments are copies of the real
                          values. The data to be passed to a function are pushed on the stack or
                          saved in registers prior to the function call. Therefore, if the function
                          should modify any of the arguments, this modification would not
                          propagate to the calling function. Therefore, a function like
                   void swap(int x, int y)
                   {
                       int temp;

                       temp = x;
                       x = y;
                       y = temp;
                   }
                          does nothing but swap two passed values, and those values are never
                          returned to the calling program. This performance is good as well as
                          bad. The bad situation is shown above when the function simply
                          does not work as expected. The good side is that it is not easy to
                          inadvertently change variable values in the calling program. The use
                          of pointers permits this problem to be avoided. The technique is called
                          passing parameters by reference. Consider the following function:

                   void swap(int* px, int* py)
                   {
                   int temp;


                   temp = *px;
                   *px = *py;
                   *py = temp;
                   }
                              Here the integers pointed to by px and py are swapped. These
                          integers are the values in the calling program. The pointer values in
                          the calling program are unaltered.
                              C makes extensive use of passing parameters by reference. Re­
                          call the first program in Chapter 1. That program has the line

                   printf(“Microcontrollers run the world!\n”);
   80   81   82   83   84   85   86   87   88   89   90