Книга: Advanced PIC Microcontroller Projects in C

4.1.3 Passing Variables by Reference to Functions

4.1.3 Passing Variables by Reference to Functions

By default, arguments to functions are passed by value. Although this method has many distinct advantages, there are occasions when it is more appropriate and also more efficient to pass the address of the arguments instead, that is, to pass the argument by reference. When the address of an argument is passed, the original value of that argument can be modified by the function; thus the function does not have to return any variables. An example follows which illustrates how the address of arguments can be passed to a function and how the values of these arguments can be modified inside the function.

Example 4.9

Write a function named Swap to accept two integer arguments and then to swap the values of these arguments. Use this function in a main program to swap the values of two variables.

Solution 4.9

The required program listing is shown in Figure 4.11. Function Swap is defined as void since it does not return any value. It has two arguments, a and b, and in the function header two integer pointers are used to pass the addresses of these variables. Inside the function body, the value of an argument is accessed by inserting the “*” character in front of the argument. Inside the main program, the addresses of the variables are passed to the function using the “&” character in front of the variable names. At the end of the program, variables p and q are set to 20 and 10 respectively.

/*************************************************************
                PASSING VARIABLES BY REFERENCE
                ==============================
This program shows how the address of variables can be passed to functions.
The function in this program swaps the values of two integer variables.
Programmer: Dogan Ibrahim
File:       SWAP.C
Date:       May, 2007
***************************************************************/
/* Function to swap two integers */
void Swap(int *a, int *b) {
 int temp;
 temp = *a; // Store a in temp
 *a = *b;   // Copy b to a
 *b = temp; // Copy temp to b
}
/* Start of the main program */
void main() {
 int p, q;
 p = 10;     // Set p = 10
 q = 20;     // Set q = 20
 swap(p, q); // Swap p and q (p=20, q=10)
}


Figure 4.11: Passing variables by reference to a function

Оглавление книги


Генерация: 1.451. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз