14 Jan Call by Reference in C
In Call by Reference, the address of the actual parameter is passed to the function. This means changes made to the formal parameter inside the function do affect the actual parameter. It’s used when you want the function to modify the original data. To pass the address, use the address-of operator &.
Actual parameters are the values or variables passed to the function when it is called. Formal parameters are the variables defined in the function declaration and definition that receive the values of the actual parameters.
Call by Reference is a method of passing arguments to a function in which the actual memory address of the argument is passed, rather than a copy of the argument.
Let us see an example of implementing Call by Reference in C programming.
In the function changeValue(), the parameter int *x is a pointer to an integer. The * operator was also used to declare a pointer variable.
The address of a is passed to the function using the address-of operator &. Inside the function, the * operator is used to dereference the pointer x, allowing direct access and modification of the value a:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Call by Reference in C #include<stdio.h> void changeValue(int *x) { *x = 10; // This change will affect the actual parameter printf("Value = %d\n", *x); } int main() { int a = 5; printf("Value of a (before) = %d\n", a); changeValue(&a); // Output is 10 since the original value changed printf("Value of a (after) = %d\n", a); // Output is 10 return 0; } |
Output
1 2 3 4 5 |
Value of a (before) = 5 Value = 10 Value of a (after) = 10 |
The above example shows how the custom function changeValue() directly modifies the value of a by using the memory address, effectively achieving call by reference.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments