Pointers and Functions
In previous lessons on Functions, we learned pass by value to function call. In this lesson, we will learn pass by reference.
Passing Address to Functions
By passing address to a function, we can change the value of the variable even outside of its scope.
Let's have a look at an example to swap two numbers
C
#include <stdio.h>
int swap(int* a, int* b) { // Pointer variables as parameters to accept address
int temp; // Creating temp variable to swap numbers
temp = *a;
*a = *b; // Changing the values in the memory location
*b = temp;
return 0;
}
int main()
{
int a = 10;
int b = 20;
swap(&a, &b); // Function call by passing address (pass by reference)
printf("a = %d, b = %d\n", a, b);
return 0;
}
int swap(int* a, int* b) { // Pointer variables as parameters to accept address
int temp; // Creating temp variable to swap numbers
temp = *a;
*a = *b; // Changing the values in the memory location
*b = temp;
return 0;
}
int main()
{
int a = 10;
int b = 20;
swap(&a, &b); // Function call by passing address (pass by reference)
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output
a = 20, b = 10
Explanation
In the above example, we pass the address of variables a and b to the function swap. The function swap accepts the address of variables a and b and stores to the pointer variables a and b. Then, we use the swaping technique to change the values of the variables a and b. Since, this algorithm changes the values in the memory location, hence it takes effect even outside of the scope of the function. Hence, this is a pass by reference.
Passing Pointer to Functions
By passing pointer to a function, we can change the value of the variable even outside of its scope.
Let's have a look at an example
C
#include <stdio.h>
void update(int* a);
int main() {
int number = 10;
int* ptr = &number;
update(ptr);
printf("number = %d\n", number);
return 0;
}
void update(int* a)
{
*a = 20;
}
void update(int* a);
int main() {
int number = 10;
int* ptr = &number;
update(ptr);
printf("number = %d\n", number);
return 0;
}
void update(int* a)
{
*a = 20;
}
Output
number = 20
Explanation
In the above example, we store the address of variable number to a pointer variable ptr. Then, we pass the pointer variable ptr to the function update. The function update accepts the pointer variable as ptr and the memory location referred by the pointer variable is updated. Hence, the value of the variable number is changed even outside of the scope of the function. This is also pass by reference.