Easy Tutorial
❮ C Function Putc C Function Sinh ❯

Calling Functions by Reference

C Functions

By passing arguments by reference, the formal parameters become pointers to the actual argument addresses. When operations are performed on the pointers, it is equivalent to performing operations on the actual arguments themselves.

Passing pointers allows multiple functions to access the object referenced by the pointer without having to declare the object as globally accessible.

/* Function definition */
void swap(int *x, int *y)
{
   int temp;
   temp = *x;    /* Save the value at address x */
   *x = *y;      /* Assign y to x */
   *y = temp;    /* Assign temp to y */

   return;
}

For more details on pointers in C, please visit the C - Pointers section.

Now, let's call the swap() function by passing values by reference:

Example

#include <stdio.h>
 
/* Function declaration */
void swap(int *x, int *y);
 
int main ()
{
   /* Local variable definition */
   int a = 100;
   int b = 200;
 
   printf("Before swap, value of a : %d\n", a );
   printf("Before swap, value of b : %d\n", b );
 
   /* Calling a function to swap the values
    * &a indicates pointer to a, i.e., address of variable a
    * &b indicates pointer to b, i.e., address of variable b
   */
   swap(&a, &b);
 
   printf("After swap, value of a : %d\n", a );
   printf("After swap, value of b : %d\n", b );
 
   return 0;
}

When the above code is compiled and executed, it produces the following result:

Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

The above example demonstrates that, unlike call by value, call by reference changes the values of a and b within the function, which actually changes the values of a and b outside the function as well.

C Functions

❮ C Function Putc C Function Sinh ❯