Introduction
Suppose you want to pass a parameter under the following conditions:
-
You need to change the value of the parameter inside the function.
-
You are interested in the changed value after the function completes.
In languages such as Pascal, you have the option of passing the parameter by reference. C, however, does not support this. As explained in the previous example, you cannot have a changed value after the function call because C uses the method of parameter passing by value. Instead, you'll have to implement the function indirectly. This is done by passing the address of the variable and changing the value of the variable through its address.
Program
main ( ) { int i; i = 0; printf (" The value of i before call %d \n", i); f1 (&i); // A printf (" The value of i after call %d \n", i); } void (int *k) // B { *k = *k + 10; // C }
Explanation
-
This example is similar to the previous example, except that the function is written using a pointer to an integer as a parameter.
-
Statement C changes the value at the location specified by *k.
-
The function is called by passing the address of i using notation &i.
-
When the function is called, the address of i is copied to k, which holds the address of the integer.
-
Statement C increments the value at the address specified by k.
-
The value at the address of i is changed to 10. It means the value of i is changed.
-
The printf statements after the function call prints the value 10, that is, the changed value of i.
Points to Remember
-
Call by reference is implemented indirectly by passing the address of the variable.
-
In this example, the address of i is passed during the function call. It does not change; only the value of the address is changed by the function.
No comments:
Post a Comment