Tuesday, March 22, 2011

Program for Call By Reference with Explanation


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

  1. This example is similar to the previous example, except that the function is written using a pointer to an integer as a parameter.
  2. Statement C changes the value at the location specified by *k.
  3. The function is called by passing the address of i using notation &i.
  4. When the function is called, the address of i is copied to k, which holds the address of the integer.
  5. Statement C increments the value at the address specified by k.
  6. The value at the address of i is changed to 10. It means the value of i is changed.
  7. The printf statements after the function call prints the value 10, that is, the changed value of i.

No comments:

Post a Comment