C Program to Implement Call by Reference

C Program to Implement Call by Reference

In C programming, function arguments are usually passed by value, which means the function receives a copy of the variable. Any changes made inside the function do not affect the original variable.

Call by reference is a technique where you pass the address of the variable to the function using pointers. This allows the function to modify the original variable directly. Call by reference is especially useful for updating multiple values in a function, swapping variables, or returning multiple results. In this tutorial, we will explore how to implement call by reference using pointers in C with clear examples and explanations.

Understanding the Problem

The goal is to create a function that modifies variables in the calling function by passing their addresses. Using pointers, we can pass the memory location of variables instead of their values.

For example, swapping two numbers requires modifying the original variables. If we pass them by value, the swap will only affect the local copies. Call by reference ensures the original numbers are changed.

The Address-of Operator (&)

In C, every variable is stored at a unique location in memory, and this location is called its address. The address-of operator (&) is used to access that address. For example, if a variable num holds the value 10, then num gives the value while &num gives the memory address where that value is stored.

#include <stdio.h>

int main() {

    int num = 10;

    printf("Value of num = %d\n", num);
    printf("Address of num = %p\n", &num);

    return 0;

}

Here, the first line prints the value stored in num, and the second prints the address of num. When using call by reference, we pass this address to a function so it can work on the original variable directly instead of a copy.

Program 1: Swapping Two Numbers Using Call by Reference

This example demonstrates how to swap two integers by passing their addresses to a function.

#include <stdio.h>

void swap(int *a, int *b) {

    int temp;
    temp = *a; // Store value of first variable
    *a = *b;   // Assign value of second variable to first
    *b = temp; // Assign stored value to second variable

}

int main() {

    int num1, num2;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

    swap(&num1, &num2); // Pass addresses to the function

    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

    return 0;

}

In this program, the function swap() receives pointers int *a and int *b. Dereferencing *a and *b allows the function to modify the original variables. This demonstrates the principle of call by reference.

Program 2: Updating Multiple Values

Call by reference is also useful for updating multiple values, such as calculating the sum and product of two numbers.

#include <stdio.h>

void calculate(int x, int y, int *sum, int *product) {

    *sum = x + y;        // Store sum in location pointed by sum
    *product = x * y;    // Store product in location pointed by product

}

int main() {

    int num1 = 5, num2 = 10;
    int sum, product;

    calculate(num1, num2, &sum, &product); // Pass addresses to store results

    printf("Sum = %d, Product = %d\n", sum, product);

    return 0;

}

Here, sum and product are passed by reference. The function writes directly to the memory locations, updating the variables in the calling function. This approach avoids returning multiple values using a single return statement.

Program 3: Modifying Arrays Using Call by Reference

When we pass an array to a function in C, we are not passing a copy of the array. Instead, the function receives the address of the first element. This means that any changes made inside the function are applied directly to the original array in the calling function. This behavior is similar to call by reference.

In the following program, the function doubleArray() multiplies each element of the array by two. Since the function works on the original array, the changes remain after the function call.

#include <stdio.h>

void doubleArray(int arr[], int size) {

    for(int i = 0; i < size; i++) {
        arr[i] = arr[i] * 2;
    }

}

int main() {

    int numbers[] = {1, 2, 3, 4, 5};
    int size = 5;

    doubleArray(numbers, size);

    printf("Updated array: ");

    for(int i = 0; i < size; i++) {

        printf("%d ", numbers[i]);

    }

    return 0;

}

In this example, the array numbers is updated directly. After the function call, the elements become 2 4 6 8 10. This demonstrates how arrays naturally behave as if they are passed by reference in C.

Program 4: Updating Structures Using Call by Reference

Call by reference is also very useful when working with structures. Structures often group related data together, and passing them by value would mean copying the entire structure. Instead, we can pass a pointer to a structure and modify its fields directly in the function.

The following program defines a Point structure with x and y coordinates. The function move() shifts the point by a given distance using call by reference.

#include <stdio.h>

struct Point {
    int x, y;
};

void move(struct Point *p, int dx, int dy) {
    p->x += dx;
    p->y += dy;
}

int main() {

    struct Point pt = {2, 3};

    printf("Before move: (%d, %d)\n", pt.x, pt.y);

    move(&pt, 5, -2);

    printf("After move: (%d, %d)\n", pt.x, pt.y);

    return 0;

}

Here, the function move() receives the address of the structure pt. By using the pointer operator ->, the function changes the values of x and y directly. The output shows the updated coordinates, proving that the structure was modified in place without copying.

FAQs

1. What is call by reference?
Call by reference is a technique where a function receives the address of a variable and can modify the original variable directly.

2. How is it different from call by value?
Call by value passes a copy of the variable, so changes inside the function do not affect the original. Call by reference passes the address, so changes are reflected outside the function.

3. Can call by reference be used with arrays?
Yes, arrays are automatically passed by reference in C, allowing functions to modify the array elements directly.

4. Is call by reference safe?
It is safe if pointers point to valid memory. Dereferencing invalid or uninitialized pointers leads to undefined behavior.

Conclusion

Call by reference using pointers is a fundamental technique in C that allows functions to modify variables directly, swap values, or return multiple results. We explored examples including swapping numbers and calculating sum and product using pointers.

Mastering call by reference is essential for effective C programming, especially when working with large datasets, dynamic memory, or complex data structures. Using pointers correctly ensures efficient and reliable code.

References & Additional Resources

A curated list of textbooks and tutorials for understanding call by reference, pointers, and memory handling in C.

  1. Kernighan, B.W., & Ritchie, D.M. (1988). The C Programming Language (2nd Edition). Prentice Hall – The foundational text explaining pointers, functions, and parameter passing in C.
  2. GeeksforGeeks: Call by Reference in C – Detailed guide on implementing call by reference using pointers in C.
  3. Tutorialspoint: C Pointers – Beginner-friendly tutorial covering pointer basics, syntax, and applications like call by reference.
  4. Cprogramming.com: Understanding Pointers – Practical explanation of pointers, including how they enable reference-based function calls.
  5. cplusplus.com: Pointer Basics – Comprehensive reference for pointer operations, memory addressing, and parameter passing techniques.

Scroll to Top