What is pass by value in C language?

Pass by value is a parameter passing mechanism in C programming where the actual value of arguments is copied to the function's formal parameters. When you pass variables to a function using pass by value, the function receives copies of the values, not the original variables themselves.

Syntax

return_type function_name(data_type parameter1, data_type parameter2, ...);

How Pass by Value Works

When using pass by value:

  • The function receives copies of the argument values
  • Changes made to parameters inside the function do not affect the original variables
  • Memory is allocated separately for function parameters

Example 1: Demonstrating Pass by Value with Swap Function

This example shows why pass by value cannot swap two numbers −

#include <stdio.h>

void swap(int a, int b) {
    int temp;
    printf("Inside function before swap: a=%d, b=%d<br>", a, b);
    temp = a;
    a = b;
    b = temp;
    printf("Inside function after swap: a=%d, b=%d<br>", a, b);
}

int main() {
    int a = 10, b = 20;
    printf("Before calling function: a=%d, b=%d<br>", a, b);
    swap(a, b);
    printf("After calling function: a=%d, b=%d<br>", a, b);
    return 0;
}
Before calling function: a=10, b=20
Inside function before swap: a=10, b=20
Inside function after swap: a=20, b=10
After calling function: a=10, b=20

Example 2: Pass by Value with Return Values

This example demonstrates how to use return values to get modified data −

#include <stdio.h>

int increment(int num) {
    num = num + 5;
    printf("Inside function: num = %d<br>", num);
    return num;
}

int main() {
    int a = 10, b, c, d;
    printf("Original value: a = %d<br>", a);
    
    b = increment(a);
    c = increment(b);
    d = increment(c);
    
    printf("a value is: %d<br>", a);
    printf("b value is: %d<br>", b);
    printf("c value is: %d<br>", c);
    printf("d value is: %d<br>", d);
    return 0;
}
Original value: a = 10
Inside function: num = 15
Inside function: num = 20
Inside function: num = 25
a value is: 10
b value is: 15
c value is: 20
d value is: 25

Key Points

  • Safe: Original variables remain unchanged, preventing accidental modification
  • Memory overhead: Copies are created for each parameter
  • Use case: Best for functions that perform calculations without modifying input data
  • Limitation: Cannot modify multiple variables directly through parameters

Conclusion

Pass by value creates copies of arguments, ensuring the original variables remain unchanged. While this provides safety, it means functions cannot directly modify the caller's variables. To modify original values, you need to use return statements or pass by reference (pointers).

Updated on: 2026-03-15T13:23:53+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements