0
0
CConceptBeginner · 3 min read

Call by Value in C: Explanation and Example

In C, call by value means passing a copy of the variable's value to a function. Changes made to the parameter inside the function do not affect the original variable outside the function.
⚙️

How It Works

Imagine you have a recipe and you give a photocopy of it to a friend. Your friend can write notes on the copy, but your original recipe stays the same. This is like call by value in C. When you call a function, the values of variables are copied and sent to the function.

Inside the function, any changes happen only to the copies, not the original variables. So, if the function changes the value, the original variable outside the function remains unchanged. This protects your original data from accidental changes.

💻

Example

This example shows how a function receives a copy of the variable. Changing the copy does not change the original variable.

c
#include <stdio.h>

void addTen(int num) {
    num = num + 10;  // Change only the copy
    printf("Inside function: num = %d\n", num);
}

int main() {
    int value = 5;
    printf("Before function call: value = %d\n", value);
    addTen(value);  // Pass copy of value
    printf("After function call: value = %d\n", value);
    return 0;
}
Output
Before function call: value = 5 Inside function: num = 15 After function call: value = 5
🎯

When to Use

Use call by value when you want to protect the original data from being changed by a function. It is useful for simple data like numbers or characters where you only need to read or temporarily modify the value inside the function.

For example, when calculating a result without changing the input, or when you want to avoid side effects that could cause bugs.

Key Points

  • Functions get a copy of the variable's value, not the original.
  • Changes inside the function do not affect the original variable.
  • Safe way to prevent accidental changes to data.
  • Used for simple data types like int, float, char.

Key Takeaways

Call by value passes a copy of the variable to the function.
Changes inside the function do not affect the original variable.
It protects original data from unintended modification.
Best for simple data types and when no change to original is needed.