Presentation is loading. Please wait.

Presentation is loading. Please wait.

Simulating Reference Parameters in C

Similar presentations


Presentation on theme: "Simulating Reference Parameters in C"— Presentation transcript:

1 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; }

2 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

3 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. a 7 b 5 7 x ? temp 5 y x 5 7 temp y

4 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); // note the use of pointers 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; }

5 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

6 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. a 7 b 5 x ? temp y a 5 b 7 x 7 temp y


Download ppt "Simulating Reference Parameters in C"

Similar presentations


Ads by Google