Skip to main content

Call by value versus call by reference

Short answer

Call by value passes a copy of arguments; changes inside the function do not affect the caller. Call by reference passes the address (pointer), so modifications directly alter the original variables.

Differentiate between call by value and call by reference (pass by value and pass by reference) with suitable example.

Call by valueCall by reference
Copies of the actual arguments are passedAddresses of the actual arguments are passed
Formal parameters are ordinary variablesFormal parameters are pointers
Changes in the function do not affect the caller's variablesChanges are made on the caller's variables
Uses extra memory for copiesNo copy of data is made; saves memory for large data
Call: swap(x, y)Call: swap(&x, &y)
Safe: original data is protectedOriginal data can be changed (risky)

C itself always passes by value; "call by reference" is obtained by passing pointers.

#include <stdio.h>
void swap_val(int a, int b)
{
    int t = a; a = b; b = t;
    printf("Inside swap_val: a=%d b=%d\n", a, b);
}
void swap_ref(int *a, int *b)
{
    int t = *a; *a = *b; *b = t;
}
int main(void)
{
    int x = 10, y = 20;
    swap_val(x, y);
    printf("After call by value: x=%d y=%d\n", x, y);
    swap_ref(&x, &y);
    printf("After call by reference: x=%d y=%d\n", x, y);
    return 0;
}

Output:

Inside swap_val: a=20 b=10
After call by value: x=10 y=20
After call by reference: x=20 y=10

swap_val swaps only its local copies, so x and y are unchanged in main. swap_ref uses the addresses, so the values are really exchanged.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 6 questions →