🔁 Call by Value and Call by Reference in C

🔁 Call by Value vs Call by Reference in C

In C programming, when we pass arguments to a function, they can be passed in two ways: Call by Value and Call by Reference. Understanding the difference between them is essential for mastering function behavior.


📌 Call by Value (Default in C)

In Call by Value, the function gets a copy of the actual argument. Changes made inside the function do not affect the original variable.

✅ Example:


#include <stdio.h>

void update(int n) {
    n = n + 10;
    printf("Inside function: %d\n", n);
}

int main() {
    int num = 20;
    update(num);
    printf("Outside function: %d\n", num);
    return 0;
}

🔍 Output:

Inside function: 30
Outside function: 20

Explanation: The original num in main() is unchanged because n was just a copy.


🔁 Call by Reference (Using Pointers)

C does not support call by reference directly, but you can simulate it using pointers. This allows the function to modify the actual value of the argument.

✅ Example:


#include <stdio.h>

void update(int *n) {
    *n = *n + 10;
    printf("Inside function: %d\n", *n);
}

int main() {
    int num = 20;
    update(&num);
    printf("Outside function: %d\n", num);
    return 0;
}

🔍 Output:

Inside function: 30
Outside function: 30

Explanation: The function changed the value at the memory address of num. So the original variable is updated.


⚖️ Difference Table

Feature Call by Value Call by Reference
Argument Type Copy of variable Address of variable
Original Value Changed? No Yes
Safety Safer (no accidental modification) Less safe (can change original)
Speed Slower with large data Faster with large data

🧠 Summary

  • Call by Value → Passes a copy → No change in original
  • Call by Reference → Passes address → Original changes
  • Use pointers in C to simulate call by reference

🧩 Practice Ideas

  1. Write a function to swap two numbers using call by value (see if it works).
  2. Write a swap function using call by reference.
  3. Create a function that increments a number using pointer.
call by value vs call by reference in c, difference between call by value and call by reference, c function pointer example, c call by reference with pointer, how to modify original variable using function in c, c programming functions tutorial

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ