0
0
CConceptBeginner · 3 min read

Call by Reference in C: Explanation and Example

In C, call by reference means passing the address of a variable to a function so the function can modify the original variable directly. Instead of sending a copy, the function works with the actual data by using pointers.
⚙️

How It Works

Imagine you want to give someone directions to your house. Instead of describing your house again and again, you just give them your address. In C, call by reference works similarly: you give the function the address (pointer) of a variable, not the variable's value itself.

This means the function can go directly to the original variable and change its value. So, any change inside the function affects the original variable outside the function too. This is different from call by value, where the function only gets a copy and cannot change the original.

💻

Example

This example shows how to use call by reference to swap two numbers by passing their addresses to a function.

c
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5, y = 10;
    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("After swap: x = %d, y = %d\n", x, y);
    return 0;
}
Output
Before swap: x = 5, y = 10 After swap: x = 10, y = 5
🎯

When to Use

Use call by reference when you want a function to modify the original data, like changing values or swapping variables. It is also useful to avoid copying large amounts of data, which saves memory and time.

Common real-world uses include updating multiple values in a function, working with arrays, or handling complex data structures efficiently.

Key Points

  • Call by reference passes the address of variables using pointers.
  • Functions can modify the original variables directly.
  • It helps save memory by avoiding copying large data.
  • Requires understanding of pointers and addresses.

Key Takeaways

Call by reference passes variable addresses so functions can change original data.
It uses pointers to access and modify variables directly.
Useful for modifying multiple values or large data efficiently.
Requires careful use of pointers to avoid errors.