60 likes | 132 Views
Simulating Reference Parameters in C. Suppose we want to implement a swap function that takes two variables and interchanges their values.
E N D
Simulating Reference Parameters in C • Suppose we want to implement a swap function that takes two variables and interchanges their values. • For example, if 7 is stored in a and 5 is stored in b, then after the call, swap(a, b), we want 5 to be stored in a and 7 to be stored in b. We might be tempted to write the following code: • #include <stdio.h> • void swap(int x, int y); • int main() • { • int a = 7; • int b = 5; • printf("\nBefore swap: a = %d \t b = %d\n", a, b); • swap(a, b); • printf("\nAfter swap: a = %d \t b = %d\n", a, b); • return 0; • }
Simulating Reference Parameters in C • void swap(int x, int y) • { • int temp = x; • x = y; • y = temp; • } • If you execute this program, you will see that it does not produce the desired result. Why? a and b are value parameters; consequently swap gets a copy of the values passed to it and stores these values in its own local variables x and y. • Output: Before swap: a = 7 b = 5 • After swap: a = 7 b = 5
Simulating Reference Parameters in C main swap (before execution) main swap (after execution) After swap returns, all variables associated with swap go away. main Since main cannot access the local variables of swap, main does not see the results.
Simulating Reference Parameters in C • What is needed is a way to pass parameters by reference instead of passing by value. • To correct the problem, we use pointers. C does not have reference parameters. • #include <stdio.h> • void swap(int *x, int *y); • int main() • { • int a = 7; • int b = 5; • printf("\nBefore swap: a = %d \t b = %d\n", a, b); • swap(&a, &b); // we must pass the address of a and the address of b • printf("\nAfter swap: a = %d \t b = %d\n", a, b); • return 0; • }
Simulating Reference Parameters in C • void swap(int *x, int *y) • { • int temp = *x; • *x = *y; • *y = temp; • } • Output: Before swap: a = 7 b = 5 • After swap: a = 5 b = 7
Simulating Reference Parameters in C main swap (before execution) main swap (after execution) Now, when swap terminates, the actual parameters in main have been modified.