C Call by Reference: Using pointers

In this article, you'll learn to pass address as an argument to the function with the help of an example.

You can not only pass variables/values to a function, but you can also pass addresses to a function. After all, address is also some kind of a value.

Since pointer store address, you can use pointer to accept that address in the function definition. Let's take an example:


Example: Passing address to a Function

 
#include <stdio.h>
void swap(int *n1, int *n2);

int main()
{
    int num1 = 5, num2 = 10;

    // address of num1 and num2 is passed
    swap( &num1, &num2);

    printf("num1 = %d\n", num1);
    printf("num2 = %d", num2);
    return 0;
}

// pointer n1 and n2 stores the address of num1 and num2 respectively
void swap(int* n1, int* n2)
{
    int temp;
    temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}

When you run the program, the output will be:

num1 = 10
num2 = 5

The address of num1 and num2 are passed to the swap() function using swap(&num1, &num2);. Pointers n1 and n2 stores them.

When the value at the addresses n1 and n2 are changed, num1 and num2 are also changed respectively. That is, if *n1 and *n2 are changed inside the swap() function, num1 and num2 are also changed inside the main() function.

Inside the swap() function, *n1 and *n2 swapped. Hence, value stored in num1 and num2 are also swapped.

Notice that, swap() is not returning anything; it's return type is void.

This technique is known as call by reference in C programming. It's because addresses are passed to the function instead of the actual value.