When we pass a copy of variables as an actual arguments while calling a function then this is known as function call by value. We have learned function call by value in previous tutorial. Today in this tutorial, we will learn function call by reference.
- Function call by reference
- Example 1: Function call by reference
- Example 2: Function call by reference
- Learn more about function
Quick links
Function call by reference in C:
- When we pass address (also known as reference) of variables as an actual arguments while calling a function then this is known as function call by reference.
- In call by reference, the address of the actual parameters is copied into the formal parameters.
- In call by reference, we can modify the value of the actual parameter by the formal parameter. Since in call by reference, a variable itself is passed.
- In call by reference, actual and formal arguments will be created in same memory location
Example 1: Consider the following example for call by reference.
#include <stdio.h>
void change(int *num)
{
/* Here, we are performing the addition on variable num, however the num
* is a pointer variable that holds the address of variable x, which means
* the addition is actually done on the address where value of x is stored.
* /
*num = *num + 9;
}
int main()
{
int x=100;
printf("Before function call x=%d \n", x);
/* In call by reference, we pass address of variable 'x', instead of passing
* the variable x. this way calling the function is knows as call by reference.
*/
change(&x);
printf("After function call x=%d \n", x);
return 0;
}
Output
Before function call x = 100
After function call x = 109
Example 2: Swapping numbers using function call by reference:
As we know in call by reference, we can modify the value of the actual parameter by the formal parameter. Since in call by reference, swap happened on he addresses of variables num1 and num2.
#include <stdio.h>
void swap(int* , int*); //function declaration
void main()
{
int num1 = 10;
int num2 = 11;
printf(" Before swapping num1= %d, num2= %d\n", num1, num2);
/* Calling swap function */
swap(&num1, &num2);
printf(" After swapping num1= %d, num2= %d", num1, num2);
}
/* Function definition */
{
void swap (int *a, int *b)
int t;
t = *a;
*a = *b;
*b = t;
}
Output
Before swapping num1= 10, num2= 11
After swapping num1= 11, num2= 10
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.